简体   繁体   中英

classList.add works but toggle doesn't

My HTML

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

My 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');
}
});
}

This adds the class of "active" on clicking the button.

But toggle doesn't work. Instead of

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

When I do,

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

the class of "active" does not toggle. console shows no error.

So I tried to check the class of "active" first & remove the class if the class exists. I know I was trying to reinvent the toggle function; as stated above, toggle wasn't working so I tried it anyway.

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

And I got a slew of error messages. This is as far as I got. I somehow felt that this wasn't going to work but just tried it anyway.

I am stumped.

Can anyone point out why classList.toggle isn't working in my code & how this can be fixed?

Thanks.

You have one too many loop. Remove the outer one:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM