Is it possible to select elements in jQuery by their HTML5 data
attributes (for example, all <div>
with data-role='footer'
)?
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.
Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.
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.
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.
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