How to Check if HTML data-* Attribute Exists Using JavaScript?

Check if HTML data-* attribute exists using JavaScript

In JavaScript, you can check whether HTML data attribute exists or not in the following ways:

Using the in Operator

You can simply use the in operator on the HTMLElement.dataset property to check if a given data attribute exists or not. For example:

<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo');

console.log('totalCount' in foo.dataset); // true
console.log('nonExistent' in foo.dataset); // false

You must specify the name of the data-* attribute in camel case (instead of dashes), and without the "data-" prefix when accessing it on the HTMLElement.dataset property.

Using Element.hasAttribute()

You can simply use the hasAttribute() method to check if the data attribute exists or not, for example, in the following way:

<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo');

console.log(foo.hasAttribute('data-total-count')); // true
console.log(foo.hasAttribute('data-non-existent')); // false

Hope you found this post useful. It was published . Please show your love and support by sharing this post.