简体   繁体   English

找到没有属性的DOM元素?

[英]find DOM elements that have no attributes?

I'm trying to find all span tags that have no attributes -- no class, no styling, no nothing. 我正在尝试查找没有属性的所有span标签-没有类,没有样式,没有任何东西。 I've been doing this: 我一直在这样做:

function hasAttributes(span) {
    if (span.outerHTML.slice(0,6) === '<span>') return true;
    return false;
}

Is there a better (faster) way to check if a particular element qualifies? 有没有更好(更快)的方法来检查特定元素是否合格?

You can use querySelectorAll() to select all spans and then use for loop to filter spans by attributes property. 您可以使用querySelectorAll()选择所有spans ,然后使用for循环按attributes属性过滤范围。 If span doesn't have any attributes it will return empty array. 如果span没有任何属性,它将返回空数组。

 var spans = document.querySelectorAll('span'); for (var i = 0; i < spans.length; i++) { if (spans[i].attributes.length == 0) spans[i].style.color = 'blue'; } 
 <span>one</span> <span class="two">Two</span> 

Check attributes property of element for length 检查元素的属性属性的长度

function hasAttributes(span){
    return span.attributes.length;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM