Reputation: 707
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?
Upvotes: 1
Views: 196
Reputation: 122037
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>
Upvotes: 2
Reputation: 171679
Check attributes property of element for length
function hasAttributes(span){
return span.attributes.length;
}
Upvotes: 0