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) { ... });
                Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!
You can use the attribute selector: $('[data-my-key]').
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
Use the Attribute Equals Selector
 $("#theDiv span[data-num='3']")
Try it!
only for example ( filter)
$('#theDiv span').filter(function(){ return $(this).data("num") == 3});
                        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