How to 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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.