Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements by HTML5 data attribute in jQuery

Tags:

html

jquery

Is it possible to select elements in jQuery by their HTML5 data attributes (for example, all <div> with data-role='footer')?

like image 813
Diogo Cardoso Avatar asked Feb 14 '11 14:02

Diogo Cardoso


People also ask

How do I select HTML element based on data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

How get data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How set data attribute in jQuery?

It should be noted that jQuery's data() doesn't change the data attribute in HTML. So, if you need to change the data attribute in HTML, you should use . attr() instead.


1 Answers

You can select on a data- attribute like any other attribute...using an attribute selector. In this case you want the attribute-equals selector, like this:

$("div[data-role='footer']") 

They are handled specially in consumption by jQuery, e.g. allowing .data() to fetch from them with correct typing...but as far as DOM traversal goes, they're just another attribute, so think of them as such when writing selectors.

like image 170
Nick Craver Avatar answered Sep 29 '22 05:09

Nick Craver