How to Check if an Element Has an Attribute in JavaScript
When you're working with the DOM, you often need to know if an HTML element has a specific attribute before you try to read or modify it. For example, you might want to check if a link has a target attribute or if an element has a custom data-* attribute.
This guide will teach you the modern, standard method for checking for the existence of an attribute using hasAttribute(). You will also learn the important distinction between this method and getAttribute().
The Core Method (Recommended): element.hasAttribute()
The Element.prototype.hasAttribute() method is the definitive tool for this job. It is designed for one specific purpose: to check if an attribute exists on an element. It returns a simple, clear boolean value.
The hasAttribute() method takes the name of the attribute as a string and returns:
true: if the attribute exists.false: if the attribute does not exist.
We'll use this <div> for our examples.
<div id="box" title="My Box" data-id="123">Box content</div>
Solution:
const box = document.getElementById('box');
// Check for the 'title' attribute
if (box.hasAttribute('title')) {
console.log('✅ The "title" attribute exists.');
} else {
console.log('⛔️ The "title" attribute does NOT exist.');
}
// Check for a non-existent attribute
if (box.hasAttribute('alt')) {
console.log('✅ The "alt" attribute exists.');
} else {
console.log('⛔️ The "alt" attribute does NOT exist.');
}
Output:
✅ The "title" attribute exists.
⛔️ The "alt" attribute does NOT exist.
This method is case-insensitive for HTML attributes, making it very reliable.
hasAttribute() vs. getAttribute()
It is important to understand the difference between these two related methods.
-
hasAttribute(name):- Purpose: To check for the existence of an attribute.
- Returns: A boolean (
trueorfalse).
-
getAttribute(name):- Purpose: To read the value of an attribute.
- Returns: A string (the attribute's value) or
nullif the attribute does not exist.
While you can use getAttribute() to check for an attribute's existence, it's less direct and can be problematic.
The Flawed getAttribute Approach
// This works, but it's not the best practice.
if (box.getAttribute('title') !== null) {
console.log('The attribute exists.');
}
The problem is that an attribute can exist with an empty string value (title=""). In this case, getAttribute('title') would return "", which is not null, so the check passes. But if you were to write if (box.getAttribute('title')), this would fail because an empty string is a "falsy" value.
For this reason, hasAttribute() is the superior and recommended method for checking if an attribute exists, as its intent is clear and its boolean return value is unambiguous.
Practical Example: Checking for a data-* Attribute
A common use case is to check if a custom data-* attribute is present before trying to read its value.
Solution:
const box = document.getElementById('box');
if (box.hasAttribute('data-id')) {
console.log('✅ The data-id attribute exists.');
// Now it's safe to get the value
const id = box.getAttribute('data-id');
console.log('The ID is:', id); // Output: "123"
} else {
console.log('⛔️ The data-id attribute does NOT exist.');
}
Conclusion
Checking for the existence of an HTML attribute is a simple task with a clear best practice.
- The
element.hasAttribute('attributeName')method is the definitive and recommended solution. It is explicit, readable, and returns a clear booleantrueorfalse. - While
element.getAttribute()can be used for a similar check, its primary purpose is to read the value of an attribute, and using it for existence checks can be less clear and more prone to errors with falsy values.
For any situation where you need to confirm an attribute is present, hasAttribute() is the right tool for the job.