Check if Element does NOT have specific Attribute using JS

avatar

Borislav Hadzhiev

Last updated: Jan 2, 2022

banner

Check out my new book

Check if Element does NOT have specific Attribute using JS #

Use the hasAttribute() method to check if an element does not have a specific attribute set, e.g. if (!el.hasAttribute('data-example')) {}. The hasAttribute method will return false if the element does not have the attribute and true otherwise.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" data-example="box">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (!box.hasAttribute('data-example')) { console.log('element does NOT have attribute'); } else { console.log('element has attribute'); }

We used the hasAttribute method to check if the data-example attribute is set on the element.

If the element has the provided attribute, the method returns true, otherwise false is returned.

index.js
// 👇️ true console.log(box.hasAttribute('data-example')); // 👇️ false console.log(box.hasAttribute('does-not-exist'));

We used the logical NOT (!) operator to negate the result returned from the hasAttribute() method.

When used with boolean values, like in the example, the operator flips the value, e.g. true becomes false and vice versa.

index.js
console.log(!true); // 👉️ false console.log(!false); // 👉️ true

If the element does not have the data-example attribute set, our if block runs, otherwise the else block runs.

index.js
const box = document.getElementById('box'); if (!box.hasAttribute('data-example')) { console.log('element does NOT have attribute'); } else { console.log('element has attribute'); }

If you need to set or remove attributes from the element, you can use the setAttribute() and removeAttribute() methods.

index.js
const box = document.getElementById('box'); box.setAttribute('title', 'Some title'); box.removeAttribute('data-example');

If you need to get the value of a specific attribute, you can use the getAttribute() method.

index.js
// 👇️ "box" console.log(box.getAttribute('data-example')); // 👇️ null console.log(box.getAttribute('does-not-exist'));

The getAttribute method returns the value of the provided attribute if it is set on the element.

If the attribute does not exist on the element the method returns null or "" (empty string), depending on the browser's implementation.

Use the search field on my Home Page to filter through my more than 3,000 articles.