如何在 javascript 函数中使用 getElementsByClassName?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14142677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:49:46  来源:igfitidea点击:

How to use getElementsByClassName in javascript-function?

javascriptdom

提问by jan199674

I cant figure out how to use multiple IDs in javascript. No problem with single ID and getElementById, but as soon as i change IDs to class and try using getElementsByClassName the function stops working. Ive read about a 100 post about the topic; still havent found the answer so i hope someone here know how to make getElementsByClassName work.

我不知道如何在 javascript 中使用多个 ID。单个 ID 和 getElementById 没有问题,但是一旦我将 ID 更改为类并尝试使用 getElementsByClassName,该函数就会停止工作。我已经阅读了大约 100 篇关于该主题的帖子;仍然没有找到答案,所以我希望这里有人知道如何使 getElementsByClassName 工作。

Heres some simple code that i have used for testing:

这是我用于测试的一些简单代码:

function change(){
    document.getElementById('box_one').style.backgroundColor = "blue";
}

function change_boxes(){
    document.getElementsByClassName ('boxes').style.backgroundColor = "green";
}


<input name="" type="button" onClick="change(document.getElementById('box_one')); change_boxes(document.getElementsByClassName('boxes'))" value="Click" />   

<div id="box_one"></div>
<div class="boxes" ></div>
<div class="boxes" ></div>

回答by Mathletics

getElementsByClassName()returns a nodeListHTMLCollection*. You are trying to operate directly on the result; you need to iterate through the results.

getElementsByClassName()返回一个*。您正在尝试直接对结果进行操作;您需要遍历结果。nodeListHTMLCollection

function change_boxes() {
    var boxes = document.getElementsByClassName('boxes'),
        i = boxes.length;

    while(i--) {
        boxes[i].style.backgroundColor = "green";
    }
}


* updated to reflect change in interface

*更新以反映界面的变化

回答by Scipion

getElementsByClassNameReturns a set of elements which have all the given class names

getElementsByClassName返回一组具有所有给定类名的元素

var elements = document.getElementsByClassName('boxes');
for(var i=0, l=elements.length; i<l; i++){
 elements[i].style.backgroundColor = "green";
}

回答by JLRishe

getElementsByClassName returns a list of elements so you would need to iterate through them and set the styles on each item one by one. It also has limited support in IE, so you might be better off using jQuery:

getElementsByClassName 返回一个元素列表,因此您需要遍历它们并逐一设置每个项目的样式。它在 IE 中的支持也有限,因此您最好使用 jQuery:

$(".boxes").css("backgroundColor", "green");