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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access