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
•
Table of Contents
•
Index
•
Reviews
•
Examples
•
Reader Reviews
•
Errata
JavaScript: The Definitive Guide, 4th Edition
By
David Flanagan
Publisher
: O'Reilly
Pub Date
: November 2001
ISBN
: 0-596-00048-0
Pages
: 936
Slots
: 1
This fourth edition of the definitive reference to
JavaScript, a scripting language that can be embedded
directly in web pages, covers the latest version of the
language, JavaScript 1.5, as supported by Netscape 6 and
Internet Explorer 6. The book also provides complete
coverage of the W3C DOM standard (Level 1 and Level 2),
while retaining material on the legacy Level 0 DOM for
backward compatibility.