首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >querySelectorAll和getElementsBy*方法返回什么?

querySelectorAll和getElementsBy*方法返回什么?
EN

Stack Overflow用户
提问于 2012-05-22 07:17:15
回答 4查看 91.3K关注 0票数 178

getElementsByClassName (以及类似的函数,如getElementsByTagNamequerySelectorAll)的工作方式是否与getElementById相同,或者它们是否返回一个元素数组?

我这样问的原因是因为我正在尝试使用getElementsByClassName更改所有元素的样式。见下文。

//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';

//works
document.getElementById('myIdElement').style.size = '100px';
EN

回答 4

Stack Overflow用户

发布于 2017-07-03 03:29:34

您可以通过运行以下命令获取单个元素

document.querySelector('.myElement').style.size = '100px';

但它将适用于类为.myElement的第一个元素。

如果你想将它应用于类的所有元素,我建议你使用

document.querySelectorAll('.myElement').forEach(function(element) {
    element.style.size = '100px';
});
票数 6
EN

Stack Overflow用户

发布于 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
票数 5
EN

Stack Overflow用户

发布于 2021-12-15 21:32:22

超级老派的解决方案:

        [].forEach.call(document.getElementsByClassName('myClass'), function (el) {
            el.style.size = '100px';
        });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10693845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档