19

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) { ... });
1
  • Yes there is, but i forgot the exact syntax, but I am sure someone will have it for you. Or you can look up the css to find selector via attribute value Commented Jul 31, 2012 at 19:40

2 Answers 2

54

Use the Attribute Equals Selector

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

Try it!

Sign up to request clarification or add additional context in comments.

4 Comments

Darn, I was just about to write that. +1 anyway.
The selector here is nor correct. It is looking for the data attribute on the element with the id, not the span!
Thanks. Upvotes all around. Works perfect (i was toying with the old example and it wasn't working but I now know why :)). Is there any way I can use the same syntax to find spans with data-num=ANYTHING? as not all spans have a data-num
@user974896 just leave out the ='3' part
1

only for example ( filter)

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

1 Comment

Did not want to itterate through all the spans and wanted a simple one liner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.