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, style, width, height, etc.

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

attribute_name should be a string, e.g. "style".

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.

Example:

const 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.

Because SVG has attribute stroke and others that does not have a DOM property.

[see Practical SVG Tutorial]

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

const xx = document.getElementById("n20652");

// example of creating a non-standard attribute
xx.setAttribute("data-user-name","John")

Class Attribute

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

See: DOM: List/Add/Remove Class Attribute

Set Element's Attribute Value

DOM: Set Element's Attribute Value

Basic DOM How-To

  1. DOM: Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. List/Add/Remove Class Attribute
  10. Add/Remove Event Handler
  11. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon