classList.add 有效但切换无效

classList.add works but toggle doesn't

我的HTML

<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>

我的js

var button = document.querySelector('#button');
var chapter = document.querySelectorAll('.chapter');
for(var i = 0; i < chapter.length; i++){
button.addEventListener('click', function(){

for(var i = 0; i < chapter.length; i++) {
chapter[i].classList.add('active');
}
});
}

这会在单击按钮时添加 "active" 的 class。

但是切换不起作用。而不是

chapter[i].classList.add('active');

当我这样做时,

chapter[i].classList.toggle('active');

"active" 的 class 不切换。控制台没有显示错误。

所以我尝试先检查 "active" 的 class,如果 class 存在,则删除 class。我知道我正在尝试重新发明切换功能;如上所述,切换不起作用,所以我还是尝试了。

if (chapter[i].contains('active')){
chapter[i].classList.remove('active');  

我收到了很多错误消息。据我所知。不知怎的,我觉得这行不通,但还是试了一下。

我难住了。

谁能指出为什么 classList.toggle 在我的代码中不起作用以及如何解决这个问题?

谢谢。

你的循环太多了。去掉外面的:

var button = document.querySelector('#button');
var chapter = document.querySelectorAll('.chapter');

button.addEventListener('click', function(){
  for(var i = 0; i < chapter.length; i++) {
    chapter[i].classList.toggle('active');
  }
});
.active{
  color: red;
}
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">button</button>

var button = document.querySelector('#button');
var chapters = document.querySelectorAll('.chapter');

  button.addEventListener('click', function(){
   for(var index = 0; index < chapters.length; index++) {
      if(chapters[index].classList.contains('active')){
        chapters[index].classList.remove('active');
      }else{
        chapters[index].classList.add('active');
      }
    }
  });
.active {
  color: red;
  }
<div class="chapter">text text text </div>
<div class="chapter">text text text </div>
<button id="button">Toggle Color</button>