admin管理员组

文章数量:1333481

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?

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?

Share Improve this question asked Feb 9, 2015 at 22:02 sawasawa 168k50 gold badges286 silver badges397 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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

document.getElementById('1').hasAttribute('data-foo')

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

本文标签: javascriptChecking for HTML5 data attribute with no valueStack Overflow