JavaScript: Get Element's Attribute Value

By Xah Lee. Date: . Last updated: .

getAttribute method

The getAttribute is generic, works in both HTML and XML.

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.

Get {Id, Clas, Href, Width} Attributes by Properties

If working in HTML (not XML), you can use a property directly for standard HTML 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: JavaScript: List/Add/Remove Class Attribute

Set Element's Attribute Value

JavaScript: Set Element's Attribute Value

BUY
Ξ£JS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc