Reading custom HTML attributes
HTML, JavaScript Juli 25th, 2007Sometimes you need to store some extra information for an HTML element, which provides additional data to your scripts. The best way to store this information is to use it as an attribute value on the element itself.
You could use a special CSS class name for a group of elements which should be handled identically, but you might lose the flexibility of CSS if these elements have completely different styles. Another possibility is to use custom (proprietary) attributes. The Dojo Toolkit makes massively use of this method. Please note that your document will not be valid (X)HTML, if you do so. Anyway, this can be quite useful but you have to be careful how to set and read the attributes.
At runtime an HTML element is presented as a DOM element object. You can add attributes by assigning them to the object.
var myElement = document.getElementById('testDiv'); myElement.mood = 'happy';
What happens if you are dealing with custom attributes that are not assigned at runtime but on the sever side? You will notice two characteristics: at first, all attribute names are lowercased by the browser and secondly this will not work as you expect.
Imagine you have this HTML element:
<div id="testDiv" foo="bar"></div>
and this script:
var myElement = document.getElementById('testDiv'); alert(myElement.foo);
This alert box will show undefined. It seems that only HTML attributes which are described in the HTML specification (such as id, lang or title) are applied as attributes to the DOM element object. Of course, there are exceptions for this rule: the Internet Explorer applies all attributes to the object.
I made a comparision sheet showing which browser supports which behavior.
Firefox 2 |
Opera 9 |
Safari 3 |
IE 7 |
|||
| attribute set by assigning | ||||||
| element.attributeName | yes | yes | yes | yes | ||
| element.getAttribute() | null | null | null | yes | ||
| attribute set by setAttribute() | ||||||
| element.attributeName | undefined | undefined | undefined | yes | ||
| element.getAttribute() | yes | yes | yes | yes | ||
| attribute set on server side | ||||||
| element.attributeName | undefined | undefined | undefined | yes | ||
| element.getAttribute() | yes | yes | yes | yes | ||
So, if you want to use custom attributes while having HTML elements which are created on runtime and on the server side, there is only one possibility: use setAttribute() and getAttribute(). This combination works in every case and in every browser.

