Check If an Attribute Exists with JavaScript hasAttribute



In this article, you will learn how to check if an attribute exists with JavaScript 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


The following example checks if the <input> element has the type attribute or the name attribute.


<input type="text" id="myid">


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