JavaScript: getAttribute

The getAttribute() method reads the value of a named HTML attribute from an element.

What you will learn

Syntax

const value = element.getAttribute('attribute-name');

Minimal example

<a id="help" href="/help.html">Help</a>
const link = document.querySelector('#help');
if (link) {
  const url = link.getAttribute('href');
  console.log(url); // /help.html
}

If the requested attribute does not exist, getAttribute() returns null. Check the result before using it as a string.

Attribute or property?

Use getAttribute() when you need the value written in the HTML attribute. For common DOM features, a property such as element.href or element.id may be more convenient and can expose a normalized value.

Common mistakes