DOM: Get Node Attribute Value

By Xah Lee. Date: . Last updated: .
node.getAttribute(attribute_name)
Return a node/element's attribute value. If the attribute doesn't exist, returns null. (browsers before 2010 may return empty string "").
node is a HTML element or XML node.
attribute_name should be a string. Example: "class", "id", etc.
// get first link
const xx = document.getElementsByTagName("a")[0];
xx.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:

This

x.getAttribute("href")

is same as

x.href

When to use getAttribute or setAttribute instead of element properties?

If you work with XML, such as scripting SVG, or has non-standard attribute such as HTML5 Custom Data Attribute.

[HTML5 Custom Data Attribute]

example:

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

[see Practical SVG Tutorial]

Example of creating a non-standard attribute:

x.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 Node Attribute Value

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js