通过类名获取元素不起作用

bri*_*e18 1 javascript function classname onload

抱歉,如果我是菜鸟,但这行代码对我来说不起作用,因为它看起来是正确的。

$(window).load(function()  {
    document.getElementByClassName("example").style.width = "50%";
    setTimeout(function () {
       document.getElementByClassName("example").style.width = "50%";
    }, 3000); 
});  
Run Code Online (Sandbox Code Playgroud)

Raj*_*amy 5

正确的函数名称是getElementsByClassName,注意复数形式。

document.getElementsByClassName("example")[0].style.width = "50%";
//Just an example for how to set the property for the first element
//we have to iterate over that collection and set property one by one
Run Code Online (Sandbox Code Playgroud)

它还会产生 a node list,所以我们必须迭代它来设置properties它。

 var elems = document.getElementsByClassName("example");
 for(var i=0;i<elems.length;i++){
   elems[i].style.width = "50%";
 }
Run Code Online (Sandbox Code Playgroud)

另请注意,这node list不是一个array. 它是一个类似数组的对象。人们通常将它们视为数组,并尝试在其上使用数组函数。这会导致错误。如果你想将它转换成数组,那么EC6中有一个方便的函数,我们可以使用它。

 var arr = Array.from(document.getElementsByClassName("example"));
Run Code Online (Sandbox Code Playgroud)

上面的代码会将 a 转换node listarray.

  • 非常感谢,你说得对,谢谢谢谢!6分钟限制过后我会给你答案 (2认同)