JavaScript Element getAttribute() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.getAttribute() is an instance method that reads an HTML attribute value from an element. Learn when it returns null, how data-* attributes work, decoded entity values, the CSP nonce security note, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Arg

attribute name

03

Returns

string or null

04

Missing

null

05

HTML

names lower-cased

06

Status

Baseline widely

Introduction

HTML attributes carry metadata: id, class, href, data-action, and more. In JavaScript you can read many reflected properties directly (el.id), but getAttribute(name) works for any attribute name as a string.

If the attribute is not present, you get null—not an empty string. That distinction matters when you branch on whether an attribute exists.

💡
Beginner tip

MDN warns: values from getAttribute() are already decoded. Never assign untrusted attribute values to innerHTML—use textContent instead to avoid XSS.

This page is part of JavaScript Element. Related DOM topics include closest() and slot.

Understanding the getAttribute() Method

Calling el.getAttribute(attributeName) looks up the attribute on el and returns its value as a string, or null if absent.

  • It is an instance method on Element.
  • In HTML documents, the attribute name argument is lower-cased before lookup (MDN).
  • Character references in markup (e.g. <) are decoded in the return value.
  • For the full Attr node, use getAttributeNode() instead.
  • CSP nonce on scripts is hidden—use el.nonce (MDN).
  • Pairs with setAttribute(), hasAttribute(), and removeAttribute().

📝 Syntax

General form of Element.getAttribute (MDN):

JavaScript
getAttribute(attributeName)

Parameters

  • attributeName — the name of the attribute whose value you want (e.g. "id", "data-id").

Return value

A string with the attribute value if it exists; otherwise null.

Common patterns

JavaScript
const el = document.getElementById("div1");

el.getAttribute("id");           // "div1"
el.getAttribute("lang");         // null (not set)

// data-* attributes
el.getAttribute("data-action");  // string or null
el.dataset.action;               // alternative for data-*

// Safe null check
const role = el.getAttribute("role");
if (role !== null) {
  console.log(role);
}

⚡ Quick Reference

GoalCode
Read an attributeel.getAttribute("href")
Read data-idel.getAttribute("data-id")
Missing attributenull
Check existence firstel.hasAttribute("disabled")
Script CSP noncescript.nonce (not getAttribute)
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Element.getAttribute().

Returns
string|null

Value or null

Baseline
widely

Since July 2015

Decoded
entities

Not raw markup

Any attr
by name

Generic reader

📋 getAttribute() vs properties vs dataset

getAttribute(name)el.id / el.hrefel.dataset.foo
Works forAny attribute nameSpecific reflected propertiesdata-* only
Return typestring or nullVaries (string, boolean, URL…)string (camelCase keys)
Missing attrnullOften "" for stringsundefined
Boolean attrsReturns string ("disabled" or null)disabled is booleanN/A
Best forGeneric attribute readsCommon IDL shortcutsClean data-* access

Examples Gallery

Examples follow MDN Element.getAttribute() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s basic example—read id and handle missing attributes.

Example 1 — Read id (MDN)

Get the value of the id attribute from a div.

JavaScript
const div1 = document.getElementById("div1");
// <div id="div1">Hi Champ!</div>

console.log(div1.getAttribute("id"));
// "div1"
Try It Yourself

How It Works

getAttribute("id") returns the attribute value as a string. For this element it matches div1.id, but getAttribute works for any name.

Example 2 — Missing Attribute Returns null (MDN)

When lang is not set, the result is null.

JavaScript
const div1 = document.getElementById("div1");

console.log(div1.getAttribute("lang"));
// null
Try It Yourself

How It Works

MDN: if the attribute does not exist, the return value is null—not undefined or "".

📈 Practical Patterns

data-* attributes, decoded entities, and common reads.

Example 3 — Read a data-* Attribute

Store custom data in HTML and read it in JavaScript.

JavaScript
const btn = document.querySelector("[data-action]");

console.log(btn.getAttribute("data-action"));
// "save"

console.log(btn.dataset.action);
// "save" (dataset alternative)
Try It Yourself

How It Works

getAttribute("data-action") and dataset.action both read the same value; choose the style that fits your codebase.

Example 4 — Decoded Character References (MDN)

HTML entities in markup are decoded in the returned string.

JavaScript
// <div data-payload="&lt;b&gt;hi&lt;/b&gt;"></div>
const el = document.getElementById("example");

console.log(el.getAttribute("data-payload"));
// "<b>hi</b>"  (decoded — do NOT use with innerHTML)
Try It Yourself

How It Works

MDN: the parser decodes references before JavaScript sees them. Treat untrusted values as text (textContent), not HTML.

Example 5 — Read class and href

Works on any element type—links, buttons, custom components.

JavaScript
const link = document.querySelector("a.card");

console.log(link.getAttribute("class"));  // "card primary"
console.log(link.getAttribute("href"));  // "https://example.com"

const missing = link.getAttribute("download");
console.log(missing === null);           // true
Try It Yourself

How It Works

getAttribute returns the literal attribute string. For links, getAttribute("href") returns the attribute value as written (which may differ slightly from the resolved link.href property).

🚀 Common Use Cases

  • Reading data-* hooks for event delegation (data-action).
  • Inspecting aria-* attributes for accessibility tooling.
  • Feature detection via custom data-feature flags in HTML.
  • Reading role, tabindex, or other attributes without IDL shortcuts.
  • Serializing element state when attributes mirror configuration.
  • Teaching the difference between attribute values and reflected properties.

🧠 How getAttribute() Looks Up Values

1

Pass an attribute name

el.getAttribute("data-id") — HTML docs lower-case the name.

Name
2

Search element attributes

The browser checks whether the element has that attribute in its attribute map.

Lookup
3

Return decoded string or null

If found, return the decoded value; if not, return null.

Result
4

Use safely in your code

Null-check, avoid innerHTML with untrusted values, use .nonce for CSP nonces.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, July 2015).
  • Missing attributes return null, not "".
  • Returned values are decoded—XSS risk if inserted as HTML (MDN).
  • getAttribute("nonce") on scripts returns ""—use script.nonce.
  • For the Attr node itself, use getAttributeNode().
  • Related: closest(), getAnimations(), slot, JavaScript hub.

Browser Support

Element.getAttribute() is Baseline Widely available (MDN: across browsers since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.getAttribute()

Read any HTML attribute value as a string — or null when missing.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Supported in legacy IE
Yes
getAttribute() Excellent

Bottom line: Use getAttribute() for generic attribute reads. Null-check results, prefer textContent for untrusted data, and use script.nonce instead of getAttribute('nonce').

Conclusion

Element.getAttribute() is the straightforward way to read any HTML attribute as a string. Remember null when missing, decoded values for security, and the nonce exception on script elements.

Continue with getAnimations(), shadowRoot, closest(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Null-check: if (val !== null)
  • Use hasAttribute() when you only need existence
  • Prefer dataset for data-* when convenient
  • Use textContent for untrusted attribute text
  • Read script.nonce for CSP nonces

❌ Don’t

  • Assign getAttribute results to innerHTML
  • Assume missing attrs return ""
  • Rely on getAttribute("nonce") on scripts
  • Confuse attribute strings with boolean IDL properties
  • Forget HTML lower-cases attribute names in documents

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.getAttribute()

Read any attribute — string or null.

5
Core concepts
📄 02

Missing

null

Check
✍️ 03

data-*

or dataset

Pattern
04

Baseline

widely available

Status
05

Security

no innerHTML

XSS

❓ Frequently Asked Questions

It returns the value of a named HTML attribute on the element as a string. If the attribute does not exist, it returns null.
No. MDN marks Element.getAttribute() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
null. Always check for null before using the value, or use hasAttribute() first.
IDL properties like id reflect specific attributes and may have different types or defaults. getAttribute() always returns a string or null for any attribute name you pass.
You can use getAttribute('data-id') or the dataset API (el.dataset.id). dataset is often cleaner for data-* names; getAttribute works for any attribute.
For CSP security, nonce values are hidden from getAttribute on script elements. Use the nonce property instead: script.nonce.
Did you know?

On HTML elements, getAttribute("ID") and getAttribute("id") are equivalent—the browser lower-cases the name before lookup. In XML documents, attribute names are case-sensitive.

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

shadowRoot →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful