Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) { ... });
like image 410
user974896 Avatar asked Jul 31 '12 19:07

user974896


People also ask

How do you find the element based on a data attribute value?

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.

How do you select an element with specific attributes?

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!

Which jQuery selector is used to retrieve all elements with the attribute data attribute name?

You can use the attribute selector: $('[data-my-key]').

How do I target a specific element in jQuery?

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.


2 Answers

Use the Attribute Equals Selector

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

Try it!

like image 172
Adam Avatar answered Oct 12 '22 08:10

Adam


only for example ( filter)

$('#theDiv span').filter(function(){ return $(this).data("num") == 3});
like image 31
voodoo417 Avatar answered Oct 12 '22 06:10

voodoo417