Name

Element.getAttribute( ): return the string value of a named attribute — DOM Level 1 Core:

Synopsis

String getAttribute(Stringname);

Arguments

name

The name of the attribute whose value is to be returned.

Returns

The value of the named attribute as a string. If the attribute is not defined, this method is supposed to return an empty string. Some implementations return null in this case, however.

Description

getAttribute( ) returns the value of a named attribute of an element. Note that the HTMLElement object defines JavaScript properties that match each of the standard HTML attributes, so you need to use this method with HTML documents only if you are querying the value of nonstandard attributes.

In XML documents, attribute values are not available directly as element properties and must be looked up by calling this method. For XML documents that use namespaces, use getAttributeNS( ).

Example

The following code illustrates two different ways of obtaining an attribute value for an HTML <img> element:

// Get all images in the document
var images = document.body.getElementsByTagName("img");
// Get the src attribute of the first one
var src0 = images[0].getAttribute("src");
// Get the src attribute of the second simply by reading the property
var src1 = images[1].src;

See Also

Element.getAttributeNode( ), Element.getAttributeNS( ), Node

Get JavaScript: The Definitive Guide, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.