querySelectorAll和getElementsBy*方法返回什么?

204
< p > getElementsByClassName(以及类似的函数,如getElementsByTagNamequerySelectorAll)是否与getElementById相同,还是它们返回元素数组?

我问这个问题是因为我正在尝试使用getElementsByClassName更改所有元素的样式。请参见以下内容。

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

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

45
线索在名称中,getElementsByClassName() 暗示复数,而 getElementById() 暗示单个元素项。 - David Thomas
1
我明白了,只是对于使用上述代码无法更改所有具有该类名的元素而不必循环遍历数组这一点感到困惑。JQuery 的方式要好得多,我只是对 JS 的方式感到好奇。 - dmo
1
可能也会有用:https://dev59.com/Um865IYBdhLWcg3wUs_z - kapa
12个回答

0

非常老派的解决方案:

        [].forEach.call(document.getElementsByClassName('myClass'), function (el) {
            el.style.size = '100px';
        });

-2

针对Drenzii的特定情况提供一个答案...

您可以创建一个函数,适用于任何word元素,并传入要转换的元素编号,例如:

// Binds `wordButtons` to an (array-like) HTMLCollection of buttons
const wordButtons = document.getElementsByClassName("word");

// Applies the `slantWord` function to the first word button
slantWord(1);

// Defines the `slantWord` function
function slantWord(wordNumber) {
  const index = wordNumber - 1; // Collection index is zero-based
  wordButtons[index].style.transform = "rotate(7deg)"; // Transforms the specified button
}
<div class="wordGameContainer">
  <button class="word word1">WORD 1</button>
  <button class="word word2">WORD 2</button>
  <button class="word word3">WORD 3</button>
  <button class="word word4">WORD 4</button>
</div>

<div>
  <button onclick="moveWord()" class="playButton">PLAY</button>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接