JavaScript: hasAttribute
The hasAttribute() method checks whether an element has a named HTML attribute and returns a boolean.
What you will learn
- How to check whether an attribute exists
- How to use the boolean result in a condition
- How hasAttribute differs from getAttribute
Syntax
const exists = element.hasAttribute('attribute-name');Minimal example
const button = document.querySelector('#save');
if (button && button.hasAttribute('disabled')) {
console.log('The button is disabled');
}The result is true when the attribute is present and false when it is absent. For boolean attributes, presence matters even if the value is an empty string.
hasAttribute and getAttribute
Use hasAttribute() when you only need to know whether an attribute exists. Use getAttribute() when you need to read its value. A missing attribute makes getAttribute() return null.
Common mistakes
- Pass an attribute name such as
disabled, not a CSS selector. - Do not compare the result with a string; it is already the boolean
trueorfalse. - Check that the target element exists before calling the method.