Web Foundations
By Tom Trumble

getAttribute (W3C DOM Core method)

By Tom Trumble




var language = document.documentElement.getAttribute('lang');

The example above retrieves the value of the lang attribute of the documentElement, and saves it to the variable language.

On an HTML page the documentElement is the root html element, so if it looked like this

<html lang="en">

Then the language variable would have the value en.


name (DOMString) required

The name of the attribute to retrieve.


Get the value of an attribute with the specified name.

This method is for working with non-namespaced attributes; to get a namespaced attribute, use the DOM 2 getAttributeNS method instead.

Return Value

The attribute value; if the attribute is not defined this method should return an empty string, however most browsers return null

This is badly broken

This method is badly broken in all browsers, particularly Internet Explorer, so you should avoid using it wherever practical.

When you need to read attributes that are also mapped to a JavaScript dot-property (such as href, style, src or event-handlers), favour that mapping instead, or consider using setAttributeNode.

No Reader comments