When I don't have access to JQuery for whatever reason, I usually perform attribute selection manually using element.hasAttribute
or element.getAttribute
.
However, there seems to be some complication here because older browsers (IE <= 8) don't support hasAttribute
. So if you want to check whether an element has a certain attribute, you need to use getAttribute
and check the return value.
if ((element.hasAttribute && element.hasAttribute("foo"))
|| (element.getAttribute("foo") != null))
{
....
}
This makes me think you may as well just forget about using hasAttribute
at all, and just always use getAttribute
. The problem is that I can't find consistent documentation on the return value of getAttribute
. In practice, it returns null
on most browsers if the attribute doesn't exist - but it also might return empty string, because that is what it's supposed to do according to the DOM 3 specification.
Unfortunately, returning an empty string leaves us with no way to disambiguate between:
<div data-my-attribute = ""></div>
and
<div></div>
So, in practice - it seems the most portable thing to do is to first check if the browser supports hasAttribute
, and if not, use getAttribute
- since IE 6-8 implement getAttribute
so that it returns null
(instead of empty string) if the attribute doesn't exist.
Is this really the best way to go about doing this? Or is there a better way to write cross-browser attribute detection in plain Javascript?
The following works well in IE6-10 (tested it in IETester), Firefox, Chrome and Safari:
function hasAttrib(element, attributeName) {
return (typeof element.attributes[attributeName] != 'undefined');
}
Here are jsfiddle and its standalone result page (for testing in older browsers).
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