The JavaScript getAttribute() method
The getAttribute() method returns the value of an element's attribute as a string, or null if the attribute isn't set. link.getAttribute("href") reads the href. It's the counterpart to setAttribute(), and works for any attribute including data-* and aria-*.
Overview
getAttribute() reads an attribute's value off an element and returns it as a string, or null when the attribute isn't there. It's the reading half of the pair with setAttribute(), and it works uniformly across standard attributes, ARIA attributes and custom data-* ones.
As with setting, there's a property-versus-attribute nuance. Reading input.value gives the field's current value (what the user has typed), while input.getAttribute("value") gives the original value from the HTML. Similarly el.getAttribute("class") returns the class string, equivalent to el.className. When you specifically want the attribute as authored, getAttribute() is the dependable choice.
For data-* attributes there's a convenient shortcut: the dataset property. el.dataset.userId reads data-user-id without a string lookup. And to check whether an attribute exists at all, hasAttribute() returns a boolean, which is cleaner than comparing getAttribute() against null.
Syntax
const value = element.getAttribute(name)
link.getAttribute("href") // "/home"
el.getAttribute("data-id") // "42"
el.getAttribute("missing") // null
Parameters
The getAttribute() method accepts the following parameters.
| Parameter | Description |
|---|---|
name |
The name of the attribute to read, e.g. "href", "src", "data-id". |
Example
<a id="link" href="/pricing" data-section="sales" style="font:15px system-ui">Pricing</a>
<pre id="out" style="font:14px ui-monospace,monospace;margin-top:8px"></pre>
<script>
const link = document.getElementById('link');
document.getElementById('out').textContent =
'href: ' + link.getAttribute('href') + '\n' +
'section: ' + link.getAttribute('data-section');
// href: /pricing / section: sales
</script>
Best practices
- Check for
null, which is returned when the attribute is absent. - Use
hasAttribute(name)for a clean presence check instead of comparing tonull. - Read
data-*attributes via thedatasetproperty when it's more convenient. - Remember
getAttribute("value")returns the original value;el.valuereturns the current one.
Frequently asked questions
What does getAttribute() return if the attribute is missing?
null. Use hasAttribute(name) if you just want to know whether it exists.What is the difference between getAttribute("value") and element.value?
getAttribute("value") returns the original HTML value; element.value returns the current value, including what the user has typed.How do I read a data attribute?
getAttribute("data-id") or the shortcut element.dataset.id.How do I check if an element has an attribute?
element.hasAttribute(name), which returns true or false.