• sdfsf
  • Search for an item that contains a specific data attribute

    I have such a list

    <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 elements containing the given data-pk-type . I am trying to execute the following unsuccessful code because .data("pkType", "foo") actually sets the data attribute foo ;

     var $links = $("#a").find("li").data("pkType", "foo"); 

    I could do something like

     var $links = $("#a").find("li", "[data-pk-type='foo']"); 

    however this would not work ... I want any element that may contain foo . Suggestions?

    +8
    javascript jquery html
    source share
    5 answers

    Description

    You must use jQuerys Attribute Contains Selector [name*="value"] .

    The attribute contains a selector [name * = "value"] : selects elements with the specified attribute with a value containing the specified substring

    Check sample and jSFiddle Demo

    Example

     $links = $("li[data-pk-type*='foo']"); alert($links.length); 

    will give you 3, so 3 elements have been found.

    Additional Information

    +11
    source share

    Try using this documentation http://api.jquery.com/attribute-contains-word-selector/

    It will be like

     var $links = $('li[data-pk-type~="foo"]',$("#a")); 
    +5
    source share

    Earlier I answered a very similar question: jQuery 1.4.4: How to find an element based on its data attribute value? . (It seems to me that you may have already seen this, since today I received an inscription on it.)

    Basically, I think you are using the wrong tool here. data- attributes should be used to store data that does not logically fit into ordinary attributes. In this case, your data-id and data-pk-type logically mapped to the regular id attribute and the regular class attribute. This is especially true because you want to find one of the many space-separated β€œtypes” β€”the exact same implementation as the classes.

    Using common attributes will make your elements much easier and faster.

     <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" classes with pk- . This may not be necessary depending on how much they are options and how many they are.

    Then you can find the elements with the usual selector:

     $('li.pk-foo'); 
    +2
    source share

    In short:

     $("#a").find("li[data-pk-type='foo']"); 
    +1
    source share

    use this $("#a").find("li[data-pk-type='foo']");

    for more details on jquery selectors from here

    +1
    source share

    All Articles