Check if data attribute Exists using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Check if data attribute Exists using JavaScript #

Use the hasAttribute() method to check if a data attribute exists, e.g. if (el.hasAttribute('data-example')) {}. The hasAttribute method returns true if the provided attribute exists, otherwise false is returned.

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 data-example="box" id="box">Box content</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('โœ… data attribute exists'); console.log(box.getAttribute('data-example')); // ๐Ÿ‘‰๏ธ "box" // ๐Ÿ‘‡๏ธ same as above console.log(box.dataset.example); // ๐Ÿ‘‰๏ธ "box" } else { console.log('โ›”๏ธ data attribute DOES not exist'); }

We used the hasAttribute method to check if a data attribute exists on an element.

The method takes the name of the attribute as a parameter and returns a boolean result:

  • true if the attribute exists on the element.
  • false if it does not.

If the data attribute exists on the element, you can get its value by using the getAttribute method or the dataset object.

index.js
const box = document.getElementById('box'); console.log(box.getAttribute('data-example')); // ๐Ÿ‘‰๏ธ "box" // ๐Ÿ‘‡๏ธ same as above console.log(box.dataset.example); // ๐Ÿ‘‰๏ธ "box"

The getAttribute method returns the value of the provided attribute on the element.

If the element does not have the attribute set, the method returns null or an empty string, depending on the browser's implementation.

Note that when using the getAttribute method to get the value of a data attribute, the whole name of the attribute has to be passed to the method.

The dataset property provides read and write access to the data attributes of an element.

If you use the dataset property to read a data attribute, you should omit the data- prefix and convert the dash-style to camelCase.

For example, if we had a data attribute data-my-example, you would access it as box.dataset.myExample.

Here is an example that sets a data attribute on the element using the dataset object.

index.js
const box = document.getElementById('box'); box.dataset.dateOfBirth = '1996-09-03'; console.log(box.dataset.dateOfBirth); // ๐Ÿ‘‰๏ธ "1996-09-03" // ๐Ÿ‘‡๏ธ true console.log(box.hasAttribute('data-date-of-birth'));

Notice that attribute names are camel-cased when accessed on the dataset object, but they are set on the DOM element using dashes.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee