Skip to content

Making jQuery.data() selector aware

When using jQuery.data() to interact with data-attributes selecting elements with that attribute will not work. jQuery('.selector').data('name'); reads the data-name="foobar" attribute from a DOMElement. This attribute could be used in a selector, say jQuery('[data-name="foobar"]').hide(). But if you use jQuery.data() to set or update such an attribute, your selector would fail.

As of jQuery 1.7 your only option is to set the data-attribute using jQuery.attr() like jQuery('.selector').attr('data-name', 'markus'). This does not run through the jQuery.data() proxy, but accesses the DOMElement's data-attribute directly.

I liked to be able to select elements by the mere fact of having such a data-attribute (rather than selecting depending on their value). I thus patched jQuery 1.7's data() function to accept a third argument updateAttr. Passing true will dispatch a jQuery.attr() call. If the given value is either of type string or number, the value is passed to jQuery.attr(). For objects the string ~defined~ is passed, as you wouldn't use them as a selector's value anyways.

See modified jQuery 1.7 or fiddle with it or comment the Issue #10668.

Update:

After discussing the issue with @MadeMyDay we came to the conclusion that a simple wrapper would suffice:

So there's actually no need for munging around jQuery core… Issue #10668 had already been closed with a "go away you moron" note.

Comments

Display comments as Linear | Threaded

No comments

The author does not allow comments to this entry