[英]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. 我试图给我的所有p元素一个类名,似乎无法弄清楚这里的问题是什么。
var para = document.getElementsByTag("p");
para.className += "myClass";
You have to loop over the collection and assign (it's also document.getElementsByTagName("p");
) 你必须遍历集合并分配(它也是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
. getElementsByTag
有一个拼写错误,应该是getElementsByTagName
。
Also para
is an array of elements, not a single one. para
也是一系列元素,而不是一个元素。 So you need to iterate against it and set className on each element, like this: 所以你需要迭代它并在每个元素上设置className,如下所示:
var para = document.getElementsByTagName("p");
for(var i=0; i<para.length; i++){
para[i].className += " myClass";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.