如何使用纯JavaScript检查data属性是否存在? [英] How to check if data attribute exist with plain javascript?
本文介绍了如何使用纯JavaScript检查data属性是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用纯JavaScript检查HTML5数据属性是否存在.我已经尝试了下面的代码段,但是没有用.
I want to check if an HTML5 data attribute exists using plain javascript. I have tried the below code snippet, but it doesn't work.
if(object.getAttribute("data-params")==="undefined") {
//data-attribute doesn't exist
}
推荐答案
Element.getAttribute
returns null
or empty string if the attribute does not exist.
您将使用 Element.hasAttribute 代码>
:
if (!object.hasAttribute("data-example-param")) {
// data attribute doesn't exist
}
或 Element.dataset
(另请参见: in 代码>运算符
):
or Element.dataset
(see also: in
operator):
if (!("exampleParam" in object.dataset)) {
// data attribute doesn't exist
}
甚至
if (!object.getAttribute("data-example-param")) {
// data attribute doesn't exist or is empty
}
这篇关于如何使用纯JavaScript检查data属性是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文