49

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

2
  • yes you can api.jquery.com/attribute-equals-selector Commented Feb 14, 2011 at 14:44
  • @Sep - That's actually not "how jQuery would do it", it will hand it off to a querySelectorAll() call if possible (and it will with an attribute selector here), not loop through the DOM itself...unless there's no other way (e.g. a custom non-CSS selector used) Commented Feb 14, 2011 at 15:03

4 Answers 4

96

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.

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

Comments

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

This simply uses the the attribute-equals-selector(docs).

There are several attribute selectors you can use (among the others).

Comments

5

jQuery Mobile recomends the $.fn.jqmData(), for example : $("div:jqmData(role='footer')")

Source: http://jquerymobile.com/test/docs/api/methods.html

Comments

0

jQuery & Zepto integration: https://github.com/kossnocorp/role

Comments

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.