Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for HTML5 data attribute with no value

I have an element that has an HTML5 data attribute with no value but just the key like this:

<div id="1" data-foo>Foo</div>

If I use dataset like this:

getElementById("1").dataset.foo

then, this will return a null value, and I cannot distinguish whether the element has data-foo attribute or not. Is there are way to check if the element has a data-foo attribute regardless of whether it has a specified value?

like image 532
sawa Avatar asked Feb 11 '23 23:02

sawa


1 Answers

You can accomplish this by checking if the element contains the attribute using the hasAttribute method:

document.getElementById('1').hasAttribute('data-foo')
like image 146
p e p Avatar answered Feb 13 '23 13:02

p e p