简体   繁体   中英

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";

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM