为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕码人8056858 2023-07-14 10:17:41
我有一些 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:65false> 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:65false> for (elem of document.getElementsByClassName("cls1")) { console.log(elem); elem.classList.toggle("cls1") }<span class="cls1">debugger eval code:1:65false> 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:63undefined> 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:65undefined我认为错误的是,document.getElementsByClassName可以找到所有七个元素,但elem.classList.toggle只适用于其中的一半。这对我来说是一个荒谬的问题。这里出了什么问题?
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

.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>


查看完整回答
反对 回复 2023-07-14
  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信