Check If an Attribute Exists with JavaScript hasAttribute

10/02/2021
Contents
In this article, you will learn how to check if an attribute exists with JavaScript hasAttribute.
Element.hasAttribute()
To check if the specified element has the specified attribute, you can use the Element.hasAttribute() method. This method returns a Boolean value indicating whether the specified element has the specified attribute or not. If the specified attribute exists, it returns true, otherwise it returns false.
const element = document.getElementById('idName');
const result = element.hasAttribute('attributeName'); // true or false
Example
The following example checks if the <input> element has the type attribute or the name attribute.
HTML
<input type="text" id="myid">
JavaScript
const element = document.getElementById('myid');
const hasType = element.hasAttribute('type');
// The element has the type attribute.
console.log(hasType); // true
const hasName = element.hasAttribute('name');
// The element doesn't have the name attribute.
console.log(hasName); // false