JavaScript Element hasAttribute() Method

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

What You’ll Learn

Element.hasAttribute() is an instance method that returns true or false depending on whether an attribute exists on the element. Learn MDN’s basic check pattern, data-* guards, boolean attributes, comparison with getAttribute(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

boolean

03

Args

attr name

04

Missing

false

05

Present

true

06

Status

Baseline widely

Introduction

Before reading an attribute value with getAttribute(), you often want to know whether the attribute is there at all. hasAttribute(name) answers that with a simple boolean — no null checks required.

MDN: the method returns whether the specified element has the specified attribute, regardless of what value it holds. An empty attribute still counts as present.

💡
Beginner tip

For boolean HTML attributes like disabled or hidden, hasAttribute("disabled") is often clearer than checking getAttribute("disabled"). Presence means true; absence means false.

This page is part of JavaScript Element. Pair hasAttribute() with getAttribute() and getAttributeNS() in your DOM toolkit.

Understanding the hasAttribute() Method

Calling el.hasAttribute(name) checks the element’s attribute list for a matching name and returns true or false.

  • It is an instance method on Element.
  • name — a string with the attribute name to look for (MDN).
  • Returns true when the attribute exists on the element.
  • Returns false when the attribute is not present.
  • Does not return the attribute value — use getAttribute() for that.
  • Works for any attribute name, including data-* and boolean attributes.
  • Case-sensitive in XML documents; HTML attribute names are typically lower-case.

📝 Syntax

General form of Element.hasAttribute (MDN):

JavaScript
hasAttribute(name)

Parameters

name — a string representing the name of the attribute (MDN).

Return value

A boolean: true if the attribute exists, false otherwise (MDN).

Common patterns

JavaScript
// MDN example
const foo = document.getElementById("foo");
if (foo.hasAttribute("bar")) {
  // do something
}

// Guard before reading
if (link.hasAttribute("href")) {
  console.log(link.getAttribute("href"));
}

// Boolean attribute
const isDisabled = button.hasAttribute("disabled");

⚡ Quick Reference

GoalCode
Check attributeel.hasAttribute("href")
data-* attributeel.hasAttribute("data-id")
Boolean attributebtn.hasAttribute("disabled")
Missing attributefalse
Read value afterel.getAttribute("href")
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Element.hasAttribute().

Returns
boolean

true / false

Baseline
widely

Since Jul 2015

Missing
false

Not present

Pair with
getAttr

Read value

📋 Attribute check APIs

hasAttribute()getAttribute()el.href (IDL)
Returnstrue / falsestring or nullTyped property value
PurposeExistence checkRead valueReflect attribute
Missing attrfalsenullDefault / empty
Boolean attrsClear presence testMay return ""Boolean property
Best forGuards & conditionalsReading any valueKnown reflected attrs

Examples Gallery

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

📚 Getting Started

MDN pattern and data-attribute guards.

Example 1 — MDN Basic Check

Test whether an element has a named attribute (MDN).

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

if (foo.hasAttribute("bar")) {
  console.log("bar attribute is present");
} else {
  console.log("bar attribute is missing");
}
Try It Yourself

How It Works

hasAttribute("bar") returns true when the attribute exists on the element, without caring about its value.

Example 2 — Guard Before getAttribute()

Check data-role exists before reading its value.

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

if (card.hasAttribute("data-role")) {
  console.log(card.getAttribute("data-role"));
} else {
  console.log("no role set");
}
Try It Yourself

How It Works

A readable guard avoids handling null from getAttribute() when the attribute was never set.

📈 Practical Patterns

Boolean attributes, comparisons, and filtering.

Example 3 — Boolean disabled

Detect boolean attributes by presence, not value.

JavaScript
const submit = document.getElementById("submit");
const reset = document.getElementById("reset");

console.log(submit.hasAttribute("disabled")); // true
console.log(reset.hasAttribute("disabled"));  // false
Try It Yourself

How It Works

<button disabled> has the attribute even when no value is written. hasAttribute("disabled") is the clearest existence test.

Example 4 — vs getAttribute() !== null

Two ways to test existence — prefer hasAttribute() for clarity.

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

const byHas = link.hasAttribute("href");
const byGet = link.getAttribute("href") !== null;

console.log(byHas);
console.log(byGet);
console.log(byHas === byGet);
Try It Yourself

How It Works

Both approaches work for ordinary attributes. hasAttribute() communicates intent better and always returns a boolean.

Example 5 — Filter by Attribute

Find list items that have a data-done marker.

JavaScript
const list = document.getElementById("tasks");
const items = list.querySelectorAll("li");
let doneCount = 0;

for (const item of items) {
  if (item.hasAttribute("data-done")) {
    doneCount++;
  }
}

console.log(doneCount);
Try It Yourself

How It Works

Loop elements and use hasAttribute() as a quick filter when presence alone matters — common for data-* flags and ARIA state attributes.

🚀 Common Use Cases

  • Guarding before getAttribute() on optional attributes.
  • Checking boolean attributes like disabled, hidden, or checked.
  • Validating data-* hooks before running component logic.
  • Feature-detecting custom attributes on third-party markup.
  • Filtering DOM nodes in scripts and tests.
  • Readable conditionals instead of getAttribute(x) !== null.

🧠 How hasAttribute() Checks Attributes

1

Pass attribute name

element.hasAttribute("href")

Args
2

Search attribute list

Browser looks for a matching name on the element (MDN).

Lookup
3

Return boolean

true if present (any value), false if missing.

Result
4

Branch or read value

Use the boolean in conditionals; call getAttribute() when you need the value.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, July 2015).
  • Returns true when the attribute exists, even if the value is an empty string.
  • Returns false when the attribute is not on the element.
  • Checks existence only — use getAttribute() to read the value.
  • Attribute names are case-sensitive in XML; use lower-case in HTML documents.
  • Related: getAttribute(), getAttributeNS(), getAttributeNames(), JavaScript hub.

Browser Support

Element.hasAttribute() 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.hasAttribute()

Check whether an element has a named attribute — returns true or false.

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
hasAttribute() Excellent

Bottom line: Use hasAttribute() for clear existence checks before getAttribute() or when testing boolean attributes.

Conclusion

Element.hasAttribute() is a simple, readable way to test whether an attribute exists on an element. It returns a boolean and pairs naturally with getAttribute() when you need the value next.

Continue with getAttribute(), getAttributeNames(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use for existence checks before getAttribute()
  • Prefer it over getAttribute(x) !== null for readability
  • Use for boolean attributes like disabled and hidden
  • Pass lower-case names in HTML documents
  • Combine with loops to filter elements by attribute

❌ Don’t

  • Use it when you need the attribute value (use getAttribute)
  • Assume it tells you if a value is “truthy”
  • Confuse presence with a non-empty value
  • Mix up attribute names (class vs className property)
  • Forget XML documents are case-sensitive for names

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.hasAttribute()

Boolean attribute existence checks.

5
Core concepts
📄 02

Missing

false

Absent
✍️ 03

Boolean

presence

disabled
04

Baseline

widely

Status
05

Pair

getAttr

Value

❓ Frequently Asked Questions

It returns a boolean indicating whether the element has the specified attribute, regardless of the attribute's value (MDN).
No. MDN marks Element.hasAttribute() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
false. When the attribute is present — even with an empty string value — it returns true.
hasAttribute() returns true/false for existence only. getAttribute() returns the attribute value as a string, or null when the attribute is missing.
Yes. If the disabled attribute is present on an element, hasAttribute('disabled') returns true even when the attribute has no value.
It is a clear, readable guard when you only need to know if an attribute exists before reading or acting on it.
Did you know?

MDN: hasAttribute() returns whether the element has the named attribute — not what its value is. An empty attribute still returns true.

More Element Topics

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

hasAttributeNS() →

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