Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give all p-elements a class name?

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";
like image 439
John Carlson Avatar asked Feb 07 '23 13:02

John Carlson


2 Answers

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.
}
like image 125
tymeJV Avatar answered Feb 11 '23 00:02

tymeJV


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";
}
like image 29
jdabrowski Avatar answered Feb 11 '23 00:02

jdabrowski