简体   繁体   中英

How to toggle list element through DOM Events in Javascript

I have a list containing three elements inside a. I'm trying to toggle on and off a CSS class which strikes the text when the list element is clicked. I've created a function and used a for loop to check for the array index of the list element that was clicked.

I've defined the following:

List Items:

<ul>
        <li class="items line-through">Watch</li>
        <li class="items line-through">Shoes</li>
        <li class="items line-through">Cake</li>
</ul>

var list = document.getElementsByClassName("line-through");

Created a function to toggle the array element from the list based on the index when "click" event happens

function checkItem(index){
    console.log("event = " + index)
    list[index].classList.toggle("line-through");
    console.log("list = " + index);}

for(var i=0; i<=list.length; i++){
    console.log("i= " + i);
    list[i].addEventListener("click", checkItem(i));}

So after my logic I've declared the for and i index with a value of zero, which is the value of the first list in the array. Then I've added the prints to check if it runs and then checked if list 0, 1, or 2 was clicked. If yes, run function and toggle list[i]. If not, i++ and verify the next one.

The problem is that now it immediately adds the toggle to the first and last items from the list. I've also tried to use querrySelectorAll("li") but then it says that list[i] is undefined, which I do not understand why, cause when verifying list[0] in the console it present the first element.

You could refactor your code and use the this keyword to target the clicked element, like this:

 document.addEventListener('DOMContentLoaded', () => { // Execute the code after the HTML content is loaded const myList = document.querySelector('.my-list'); const listElements = Array.from(myList.children); listElements.forEach( li => { li.addEventListener('click', checkItem); }); function checkItem() { // The `this` keyword is the clicked element this.classList.toggle('line-through'); } });
 <ul class="my-list"> <li class="items line-through">Watch</li> <li class="items line-through">Shoes</li> <li class="items line-through">Cake</li> </ul>

This will add the event listener to all the children elements of the list and toggle the line-through class on the clicked one.

Keep in mind that when manipulating the DOM, you should wrap your JS code inside a DOMContentLoaded event listener to prevent selecting elements that are not yet present on the page.

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