6

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?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

7

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

document.getElementById('1').hasAttribute('data-foo')
p e p
  • 6,593
  • 2
  • 23
  • 32
2

If the element does not feature the data-foo attribute, a call to dataset.foo will return undefined, rather than null (or an empty string in the case of an empty attribute).

You should check the actual value, as follows:

var fooVal = document.getElementById('div1').dataset.foo;

// data-foo is not present at all:
if( fooVal === undefined )
{

} 

// data-foo is present but empty
if( fooVal === '' )
{

} 

Of course, you could cast the logic to a simple boolean:

var hasFoo = ( document.getElementById('div1').dataset.foo !== undefined );

jsFiddle Demo

BenM
  • 52,573
  • 26
  • 113
  • 168
  • 1
    Not correct. If data-foo is present, fooVal is the empty string, not null. – Alohci Feb 09 '15 at 22:17
  • @Alohci You are right. So the first form is wrong but the second form is correct, I guess. – sawa Feb 09 '15 at 22:18
  • Is there any possibility of an explicitly set value being `undefined`? – sawa Feb 09 '15 at 22:20
  • 2
    @sawa - not via the markup attribute, no. Some pedants however will argue that you shouldn't do a `=== undefined` test because it's theoretically possible in JavaScript for `undefined` to be defined!, and that therefore your test should be `=== void 0` because `void 0` always evaluates to undefined. I'm not one of them. – Alohci Feb 09 '15 at 22:27
  • @Alohci I don't believe the ability to define the `undefined` value has been a thing for many years.. So everyone should be safe to use it now. – WORMSS Mar 27 '18 at 10:54