A couple of useful ‘vanilla’ Javascript methods that are a little ignored although they have been around since DOM2.
The hasAttributes() Method
This checks to see if an element has any attributes and a boolean value – true
for yes indeedy and false
for nope soz is returned.
Take this HTML snippet:
<p class="someClass">We are classy</p> <p class="someClass">We are classy</p> <p>I lack class</p> <p class="someClass">We are classy</p>
If we need to identify the <p>
without a class then we could use the hasAttributes()
method as follows:
document.getElementById('findClassless').addEventListener('click', function(){ var noItems = document.getElementsByTagName('p').length; for(var i=0; i<noItems ; i++){ if(!document.getElementsByTagName('p').item(i).hasAttributes()){ document.getElementsByTagName('p').item(i).setAttribute('class', 'someClass'); document.getElementsByTagName('p').item(i).innerHTML = "Now I'm classy!"; }; } });
Line 4 checks each <p>
to see if it has any attributes. If the <p>
does not have any attributes then we will add an attribute with setAttribute
.
The hasAttribute() Method
The hasAttribute()
can be used to look for one specific attribute. Therefore our example above could be amended to use hasAttribute('class')
.
document.getElementById('findClassless').addEventListener('click', function(){ var noItems = document.getElementsByTagName('p').length; for(var i=0; i<noItems ; i++){ if(!document.getElementsByTagName('p').item(i).hasAttribute('class')){ document.getElementsByTagName('p').item(i).setAttribute('class', 'someClass'); document.getElementsByTagName('p').item(i).innerHTML = "Now I'm classy!"; }; } });