I have a list like so
<ul id="a">
<li data-id="i1" data-pk-type="foo bar">sdfsf</li>
<li data-id="i2" data-pk-type="foo">sdfs</li>
<li data-id="i3" data-pk-type="bar baz">sfdsf</li>
<li data-id="i4" data-pk-type="qux foo">sfds</li>
<li data-id="i5" data-pk-type="baz">sdff</li>
</ul>
I want to find all the elements that contain a given data-pk-type
. I am trying the following unsuccessful code because .data("pkType", "foo")
actually sets the data attribute to foo
;
var $links = $("#a").find("li").data("pkType", "foo");
I could do something like
var $links = $("#a").find("li", "[data-pk-type='foo']");
however that wouldn't work as well… I want any element that might contain foo
. Suggestions?
You should use jQuerys Attribute Contains Selector [name*="value"]
.
Attribute Contains Selector [name*="value"]: Selects elements that have the specified attribute with a value containing the a given substring
Check out the sample and jSFiddle Demonstration
$links = $("li[data-pk-type*='foo']");
alert($links.length);
will give you a 3, so 3 elements was found.
Try based on this documentation http://api.jquery.com/attribute-contains-word-selector/
It will be like
var $links = $('li[data-pk-type~="foo"]',$("#a"));
I've previously answered a very similar question: jQuery 1.4.4: How to find an element based on its data-attribute value?. (I fancy you may have seen it already, since I got an upvote on it this afternoon.)
Basically, I think you're using the wrong tool here. data-
attributes should be used for storing data that doesn't logically fit into the normal attributes. In this case, your data-id
and data-pk-type
logically map to the normal id
attribute and to the normal class
attribute. This is especially true because you want to find one of a set of space-separated "types" – exactly the same implementation as classes.
Using normal attributes will make your elements much easier and quicker to find.
<ul id="a">
<li id="i1" class="pk-foo pk-bar">sdfsf</li>
<li id="i2" class="pk-foo">sdfs</li>
<li id="i3" class="pk-bar pk-baz">sfdsf</li>
<li id="i4" class="pk-qux pk-foo">sfds</li>
<li id="i5" class="pk-baz">sdff</li>
</ul>
Note that I have "namespaced" the classes with pk-
. This may not be necessary depending on how variant and numerous they are.
You can then find the elements with a normal selector:
$('li.pk-foo');
In Short:
$("#a").find("li[data-pk-type='foo']");
use this $("#a").find("li[data-pk-type='foo']");
for more info read about jquery selectors from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With