JavaScript: getAttribute
The getAttribute() method reads the value of a named HTML attribute from an element.
What you will learn
- How to read an attribute value
- What the method returns when an attribute is missing
- How getAttribute differs from a DOM property
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
- Pass an attribute name such as
href, not a CSS selector. - Do not assume the result is always a string; a missing attribute produces
null. - Use
hasAttribute()when you only need to know whether the attribute exists.