Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript's getAttribute method across browsers

DZone's Guide to

JavaScript's getAttribute method across browsers

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

ie-wtf

Sometimes you might want to read the “class” attribute value of an HTML tag (for example div) from your JavaScript for processing. Almost all major JavaScript frameworks provide method to read attribute values, using which we can easily get the value of “class” attribute.

But if you’re not allowed to use any such libraries, then you would have to rely on the browser’s built-in method getAttribute to achieve the functionality.

Before you use the JavaScript’s getAttribute method, do keep in mind that its implementation (especially for “class” attribute) differs from browser-to-browser. I.e., IE does it differently from what other browsers are doing (as you would have expected!).

The below code would alert the class value of “myElem” in all browser’s. But, Internet Explorer would just say “null”!

var elem = document.getElementById("myElem");
alert(elem.getAttribute("class"));

To make that work in Internet Explorer, change to “className” and see what happens!

var elem = document.getElementById("myElem");
alert(elem.getAttribute("className"));

Now the above code will work only in Internet Explorer but will fail in all other browsers. :)

So what’s the correct solution that works in all browser? Well, don’t use the getAttribute() method at all. Instead, use the property className to get the class attribute value.

Here’s the cross-browser solution:

var elem = document.getElementById("myElem");
alert(elem.className);

That should do the trick!

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Veera Sundar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}