JS: 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 JS: 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: JS: List/Add/Remove Class Attribute

Basic DOM Methods Topic

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