Skip to content

Instantly share code, notes, and snippets.

@cburgdorf
Created October 30, 2012 12:31
Show Gist options
  • Save cburgdorf/3979912 to your computer and use it in GitHub Desktop.
Save cburgdorf/3979912 to your computer and use it in GitHub Desktop.
YOU:
Hey #jQuery guys! What's the best way to check if an element has a specific data attribute? Is there only $.attr() ?
YOU SAY:
(typeof($el.data('name')) != 'undefined') { … }
..is what you currently use.
ME:
You can use that. Just be aware that it will also return true even if the "data-name" does not exist on the element. Never. Ever. Existed.
Why is that? Well, because jQuery returns true either if the "data-name" exists OR the "name" exists inside the $.cache object (which has nothing to do with html5 data attributes)
Even worse: if you set something with $element.data('name'), don't expect it to create an html5 data-name attribute. It won't! Instead it will store it inside $.cache.
If that's what you want - go for it.
If what you really want is to check for html5 data attributes use this:
(function( $ ) {
$.fn.hasAttr = function(attr) {
var value = this.attr(attr);
/*if you wonder about this line, here is why
http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element */
return typeof value !== 'undefined' && value!== false
};
$.fn.hasDataAttr = function(attr) {
return this.hasAttr('data-' + attr);
};
})( jQuery );
@0x-r4bbit
Copy link

Maybe I get something wrong but, my code returns false when there isn't a data-attribute that fits to the given name.

@cburgdorf
Copy link
Author

@cburgdorf
Copy link
Author

The point is: data() does not check for data attributes exclusively. In fact the ability to check for data attributes using data() was just added in jquery 1.5 I think. While data() has been around for pretty long time already. So data() checks for existence in $.cache AND in data attributes. If that's what you want, go for it. Just be aware that it could also return true even if there is no data attribute. And if other parts of the system rely on html5 data attributes existence. Better check for that exclusively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment