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

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:


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

// is equivalent to

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")

[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
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon