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:
Foo
If I use dataset like this: getElementById(Solution 1:
You can accomplish this by checking if the element contains the attribute using the hasAttribute
method:
document.getElementById('1').hasAttribute('data-foo')
Solution 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 );
Post a Comment for "Checking For HTML5 Data Attribute With No Value"