How to give all p-elements a class name?

I am trying to give all my p-elements a class name, it may not seem like the problem is here.

var para = document.getElementsByTag("p");
para.className += "myClass";
+4
source share
2 answers

You need to loop through the collection and assign (it 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.
}
+7
source

There is a typo in getElementsByTag, it should be getElementsByTagName.

It parais also an array of elements, not just one. Therefore, you need to iterate against it and set className for each element, for example:

var para = document.getElementsByTagName("p");
for(var i=0; i<para.length; i++){
    para[i].className += " myClass";
}
+1
source

All Articles