DekGenius.com
Team LiB   Previous Section   Next Section
Element.getAttribute( ) return the string value of a named attribute

Availability

DOM Level 1 Core

Synopsis

String getAttribute(String name);

Arguments

name

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

Returns

The string value of the named attribute. If the attribute does not have a value specified in the document and does not have a default value specified by the document type, the return value is the empty string ("").

Description

getAttribute( ) returns the value of a named attribute of an element. In HTML documents, attribute values are always strings, and this method returns the complete attribute value. Note that the objects that represent HTML elements also implement the HTMLElement interface and one of its tag-specific subinterfaces. Therefore, all standard attributes of standard HTML tags are also available directly as properties of the Element object.

In XML documents, attribute values are not available directly as element properties and must be looked up by calling a method. For many XML documents, getAttribute( ) is a suitable method for doing this. Note, however that in XML attributes may contain entity references, and in order to obtain complete details about such attributes, you must use getAttributeNode( ) to obtain the Attr node whose subtree represents the complete attribute value. The Attr nodes for an element are also available in an attributes[] array inherited from the Node interface. For XML documents that use namespaces, you may need to use getAttributeNS( ) or getAttributeNodeNS( ).

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( ), Node.attributes

    Team LiB   Previous Section   Next Section