I'm trying to give all of my p-elements a class name, can't seem to figure out what the problem is here.
var para = document.getElementsByTag("p");
para.className += "myClass";
You have to loop over the collection and assign (it's also document.getElementsByTagName("p");
)
for (var i = 0; i < para.length; i++) {
para[i].className += " myClass";
// ^^^
//As @nnnnnn pointed out - a space beforehand will ensure the class is added to existing classes - and not added as a single word.
}
There is a typo in getElementsByTag
, should be getElementsByTagName
.
Also para
is an array of elements, not a single one. So you need to iterate against it and set className on each element, like this:
var para = document.getElementsByTagName("p");
for(var i=0; i<para.length; i++){
para[i].className += " myClass";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With