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?
2 Answers
Reset to default 7You 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
版权声明:本文标题:javascript - Checking for HTML5 data attribute with no value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742242736a2438934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论