getAttribute (W3C DOM Core method)

Tweet

Returns

DOMString

Example

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.

Arguments

name (DOMString) required

The name of the attribute to retrieve.

Description

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.

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments