如何使用纯JavaScript检查数据属性是否存在?

85
我想使用纯JavaScript来检查HTML5数据属性是否存在。 我尝试了下面的代码片段,但它不起作用。
if(object.getAttribute("data-params")==="undefined") {
   //data-attribute doesn't exist
}

if(typeof obj["data-attribute"] !== "undefined"){ // code here } - Ashish Kumar
11个回答

154

Element.getAttribute 方法会在属性不存在时返回 null 或空字符串。

如果要判断元素是否具有某个属性,可以使用Element.hasAttribute 方法:

if (!object.hasAttribute("data-example-param")) {
    // data attribute doesn't exist
}

或者使用Element.dataset(另请参阅:in 运算符):

if (!("exampleParam" in object.dataset)) {
    // data attribute doesn't exist
}

甚至

if (!object.getAttribute("data-example-param")) {
    // data attribute doesn't exist or is empty
}

3
为什么被选为答案的回答会被标记为负分? - Gerico
3
在我看来,"在数据集中"可能是最干净的方法。它处理已经存在的哈希而不是查找一个带有字符串属性的方法,这有点奇怪并且可能更慢。 - FlorianB
3
请注意,对于属性名data-example-param,在使用dataset时大小写和破折号的处理方式会与使用hasAttributegetAttribute时不同。 - Flimm

7

检查是否为null也得出了解决方案。

if (object.getAttribute("data-example-param") === null) {
//data attribute doesn't exist
 }else{
 //data attribute exists
 }

5
您可以使用数据集 API。

HTMLElement.dataset

HTMLElement.dataset只读属性允许以读取和写入模式访问元素上设置的所有自定义数据属性(data-*)。它是DOMString的映射,每个自定义数据属性都有一个条目。

遗憾的是,这在IE10中不起作用,但我相信肯定有某个替代方法。

这里是一个例子

var containerData  = document.querySelector('#container').dataset,
    contentData  = document.querySelector('#content').dataset;

// Check if dataset is empty or not.
console.log(Object.keys(containerData).length === 0);
console.log(Object.keys(contentData).length === 0);

// Check for specific data
if (containerData.hasOwnProperty('bar')) {
  console.log(containerData.bar);
}

// Here is the dataset
console.log(containerData);
<div id="container" data-foo="bar" data-bar="foo">
  <div id="content">
    Content
  </div>
</div>


3
你发布的代码无法按照你的期望工作,你在这里做的是检查指定属性("data-params")的属性值是否等于"undefined",而这只有在属性值为data-params="undefined"时才会返回true
if (object.getAttribute("data-params") === "undefined") {
   // the "data-params" attribute-value is exactly "undefined"
   // note that `getAttribute()` is a 
}

我猜想你想做的是:
var typeOfObjectAttribute = typeof object.getAttribute("data-params");

if (typeOfObjectAttribute === null || typeOfObjectAttribute === "") {
   // data-params attribute doesn't exist on that Node.
}

注意,根据Mozilla开发者网络(在下面Element.getAttribute()的参考文献中),指出:

getAttribute()返回元素上指定属性的值。如果给定的属性不存在,则返回的值将是null""(空字符串)...

值得注意的是,getAttribute()是Element节点的方法,而不是通用对象的方法。
顺便提一下,您也可以使用以下方法(再次测试属性是否未设置):
// here we look to see if the 'params' key is present in the
// HTMLElement.dataset object of the element, and then invert
// that result using the '!' operator, to check that the
// attribute *isn't* present:
if (!('params' in document.getElementById('elementID').dataset)) {
    // the data-params attribute is not present.
}

参考资料:

2
要查看特定的自定义 HTML5 data-* 属性是否存在于给定的 HTML5 元素中,只需检查元素的 datasetdataset 是一个 DOMStringMap 对象,因此您可以使用 hasOwnProperty() 方法:
if (element.dataset.hasOwnProperty('params')) {

  [... CODE HERE...]

}

2
唯一对我有用的是这个。最初的回答。
if(typeof object.dataset.sheet === "undefined") {
  console.log('Data attribute does not exist');
}

2
甚至更简单:

最初的回答

if (object.dataset.sheet !== undefined) {
  // the "data-sheet" attribute exists
}

1

尝试使用typeof

if(typeof object.getAttribute("data-params") === "undefined") {
   console.log('data-attribute doesn't exist');
}

0
如果有人来到这里知道他们要查找的数据属性,那么可以使用以下方法检查它是否存在:
HTML:
<input id="your-element" data-type="something">

JS:

const element = document.querySelector('#your-element');
if( element.dataset.type === 'something'){
// Do something
}

当然,上面例子中data-type中的type是一个自定义名称,数据属性可以有任何名称,例如data-catsdata-dogs等等... ...


0

你可以只进行假值检查

if(!object.getAttribute("data-params")) {
   //data-attribute doesn't exist
}

因为 getAttribute 可能返回 null 或空字符串

你也可以使用 object.hasAttribute("data-params") 来检查属性是否存在


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接