Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStefan Cutajar
7,747 Pointstoggle a class using javascript
Hi I am doing a small app for practice and I want a class too be toggled to the element when its clicked. I have managed to add the class when on click event using this code : for(let i = 0; i < li.length; i += 1){ li[i].addEventListener( 'click', () => { event.target.className = 'checked'; });} However when I used .toggle or className.toggle the class fail to be added/ removed
1 Answer
Tim Acker
Front End Web Development Techdegree Graduate 31,247 Pointsconst liElements = document.querySelectorAll('li');
liElements.forEach((li, i) => {
li.addEventListener('click', () => li.classList.toggle('checked'));
});
Try something like this.
Stefan Cutajar
7,747 PointsStefan Cutajar
7,747 PointsThanks it worked :D Is it possible to be done using a normal for loop?