getElementsByClassName
(以及类似的函数,如getElementsByTagName
和querySelectorAll
)的工作方式是否与getElementById
相同,或者它们是否返回一个元素数组?
我这样问的原因是因为我正在尝试使用getElementsByClassName
更改所有元素的样式。见下文。
//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
发布于 2017-07-03 03:29:34
您可以通过运行以下命令获取单个元素
document.querySelector('.myElement').style.size = '100px';
但它将适用于类为.myElement的第一个元素。
如果你想将它应用于类的所有元素,我建议你使用
document.querySelectorAll('.myElement').forEach(function(element) {
element.style.size = '100px';
});
发布于 2018-11-25 12:06:33
/*
* To hide all elements with the same class,
* use looping to reach each element with that class.
* In this case, looping is done recursively
*/
const hideAll = (className, i=0) => {
if(!document.getElementsByClassName(className)[i]){ //exits the loop when element of that id does not exist
return;
}
document.getElementsByClassName(className)[i].style.visibility = 'hidden'; //hide element
return hideAll(className, i+1) //loop for the next element
}
hideAll('appBanner') //the function call requires the class name
发布于 2021-12-15 21:32:22
超级老派的解决方案:
[].forEach.call(document.getElementsByClassName('myClass'), function (el) {
el.style.size = '100px';
});
https://stackoverflow.com/questions/10693845
复制相似问题