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, example: "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.


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

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

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

DOM How-To

  1. 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. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog