DOM: Get Element's Attribute Value

By Xah Lee. Date: . Last updated: .

node.getAttribute(attribute_name) → Return a element's attribute value.

Attributes are things like class, id, image tag's width, height, etc.

If the attribute doesn't exist, returns null. (browsers before 2010 may return empty string "")

The attribute_name should be a string. The node is a HTML element object. 〔►see DOM: Get Elements by ID, Tag, Name, Class, CSS Selector〕.

// get the value of attribute “href” in first link element
document.getElementsByTagName("a")[0].getAttribute("href");

As of , this works in all major browsers.

Using Properties for Standard Attributes

For HTML elements (not XML), usually there's a corresponding property for standard attributes. That is, you can directly do:

etc.

var myE = document.getElementsByTagName("a")[0];

myE.getAttribute("href");
// is equivalent to
myE.href

When to use getAttribute or setAttribute instead of element properties?

If you work with XML, such as scripting SVG, you should use getAttribute/setAttribute.

For example XML's arbitrary attributes, such as SVG's stroke="…".

If you work with HTML with any non-standard or uncommon HTML attribute. For example, things like the HTML5 Custom Data Attribute that begin with data-. See: HTML5 Custom Data Attribute

// example of creating a non-standard attribute
var xx = document.getElementById("e22")
xx.setAttribute("stroke","red")

〔►see Practical SVG Tutorial

Class Attribute

When working with the attribute class, there are more convenient methods.

See: DOM: List/Add/Remove Class Attribute

Basic DOM Methods Topic

  1. DOM: Basic DOM Methods
  2. DOM: Get Elements by ID, Tag, Name, Class, CSS Selector
  3. DOM: Get Element's Attribute Value
  4. DOM: Set Element's Attribute Value
  5. DOM: List/Add/Remove Class Attribute
  6. DOM: Node Type, Node Name, Node Value
  7. DOM: Navigate DOM Tree
  8. DOM: Add / Remove Event Handler
Like what you read? Buy JavaScript in Depth