抱歉,如果我是菜鸟,但由于某些原因,这行代码看起来正确,因此对我不起作用。
$(window).load(function() {
document.getElementByClassName("example").style.width = "50%";
setTimeout(function () {
document.getElementByClassName("example").style.width = "50%";
}, 3000);
});
最佳答案
正确的函数名称是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
它还会产生一个节点列表
,所以我们必须迭代它来为它设置properties
。
var elems = document.getElementsByClassName("example");
for(var i=0;i<elems.length;i++){
elems[i].style.width = "50%";
}
另请注意,节点列表
不是数组
。它是一个类似对象的数组。人们通常将它们视为数组,他们会尝试在其上使用数组函数。这将导致错误。如果您想将其转换为数组,EC6 中提供了一个方便的函数,我们可以使用它。
var arr = Array.from(document.getElementsByClassName("example"));
上面的代码会将一个节点列表
转换成一个数组
。
关于javascript - 按类名获取元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803074/