user974896
user974896

Reputation: 1813

Find an element with a specific data attribute jQuery

I understand that I can always iterate down the DOM tree and check every element for a data field and if the value is correct but I would like a cleaner solution. For example

    <div id="theDiv">
       <div>
         <span data-num="3" ></span>
         OTHER HTML
       </div>
       <div>
         <div><span data-num="23"></span><div>
         OTHER HTML
       </div>
       <div>
         <span data-num="3"></span>
         OTHER HTML
       </div>
    </div>

Is there a jQuery one liner to find all spans with data-num=3? I know I can find all spans by

  $("#theDiv").find(span).each(function(e) { ... });

but I would like something like

  $("#theDiv").find(span > data-num=3).each(function(e) { ... });

Upvotes: 19

Views: 41949

Answers (2)

voodoo417
voodoo417

Reputation: 12091

only for example ( filter)

$('#theDiv span').filter(function(){ return $(this).data("num") == 3});

Upvotes: 1

Adam
Adam

Reputation: 44919

Use the Attribute Equals Selector

 $("#theDiv span[data-num='3']")

Try it!

Upvotes: 54

Related Questions