This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
                            
                                (9个答案)
                            
                    
                2年前关闭。
        

    

我正在学习JS中的新循环结构,但无法获得while循环以使用for循环的方式对元素进行更改。

在以下代码中,它引发错误“无法设置属性'background'的未定义”。这似乎与变量mydiv有关?

有人对这可能是为什么还是这里发生的事情有任何倾向吗?

JS

var mydiv = document.getElementsByTagName('div');

var i = 0;

while (i < mydiv.length) {
 mydiv.style.background = "yellow";
 i++;
}


的CSS

body {display: flex;}
.box {width: 100px; height: 100px; background: red; margin: 0
10px;}


的HTML

<div class="box"></div>
<div class="box"></div>

最佳答案

您需要通过循环内的索引访问元素

var mydiv = document.getElementsByTagName('div');

var i = 0;

while (i < mydiv.length) {
 mydiv[i].style.background = "yellow";
 i++;
}

关于javascript - While循环引发错误-Javascript ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47585578/

10-09 15:11
查看更多