I'm trying to find all span
tags that have no attributes -- no class, no styling, no nothing. 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. If span doesn't have any attributes it will return empty array.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.