elem.classList.toggle 不适用于所有元素

我有一些 HTML 代码,如下所示:


<html><head></head><body>

<span class="cls1">test</span>

<span class="cls1">test</span>

<span class="cls1">test</span>

<span class="cls1">test</span>

<span class="cls1">test</span>

<span class="cls1">test</span>

<span class="cls1">test</span>

<style>

  .cls1 {

    color: red;

  }  

</style>

</body></html>

然后我想使用一些 JavaScript 代码来切换cls1这些元素的类。我输入了这些行。输出也如下:


> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

false

> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

false

> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }

<span class="cls1">

debugger eval code:1:65

false

> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.add("cls1") }

undefined

> for (elem of document.getElementsByTagName("span")) { console.log(elem); elem.classList.add("cls1") }

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

<span class="">

debugger eval code:1:63

undefined

> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); }

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

<span class="cls1">

debugger eval code:1:65

undefined

我认为错误的是,document.getElementsByClassName可以找到所有七个元素,但elem.classList.toggle只适用于其中的一半。这对我来说是一个荒谬的问题。这里出了什么问题?


慕码人8056858
浏览 120回答 1
1回答

子衿沉夜

请.querySelectorAll()改为使用,与往常一样,返回的集合是实时的,这意味着它始终反映以调用该函数的元素为根的 DOM 树的当前状态。当与名称匹配的新元素添加到子树时,它们会立即出现在集合中。同样,如果与名称不匹配的现有元素已调整其类集以使其匹配,则它会立即出现在集合中。反之亦然;当元素不再与名称集匹配时,它们会立即从集合中删除。let elements = document.querySelectorAll(".cls1");for(let elem of elements) {  console.log(elem);  elem.classList.toggle("cls1");}.cls1 {  color: red;}  <span class="cls1">test</span><span class="cls1">test</span><span class="cls1">test</span><span class="cls1">test</span><span class="cls1">test</span><span class="cls1">test</span><span class="cls1">test</span>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript