Validate HTML5 data attribute without value

I have an element that has an HTML5 attribute datawithout a value, but only such a key:

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

If I use datasetas follows:

getElementById("1").dataset.foo

then this will return a null value, and I cannot tell if the element has an attribute data-fooor not. Is there a way to check if an element has an attribute data-fooregardless of whether it has a specified value?

+3
source share
2 answers

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

document.getElementById('1').hasAttribute('data-foo')
+6
source

data-foo, dataset.foo undefined, null ( ).

, :

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 === '' )
{

} 

, :

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

jsFiddle Demo

+1

Source: https://habr.com/ru/post/1617449/


All Articles