简体   繁体   中英

JavaScript apply classList.toggle to only onclick element

I have a function in my todo list app that generates my HTML:

function updateResults() {
            listItems = todos.reduce((result, item) => {
                result += `<li class="todo">${item}<div class="controls">
                <span class="check" onclick="checkItem()"></span><span class="delete">&#x1F5D1</span></div></li>`;
                return result;
            }, '');
            resultElement = document.getElementById('result');
            // Set inner HTML
            resultElement.innerHTML = listItems;
        } 

When the 'check' span is clicked on one of the generated items, I want only that item to be checked, but I'm only able to toggle ALL list items at a time.

function checkItem() {
            [...document.getElementsByClassName('check')].forEach(function (item) {
                item.classList.toggle('checked');
            });
        }

I want to be using the 'this' keyword here right? I've tried a bunch of different syntax but have not been able to to target just the element that was clicked with my 'checked' class.

Thanks kindly.

I suggest removing the inline onclick (and your checkItem function) and creating an event listenter like this

// listen to all clicks on your page
window.addEventListener('click', (event) => {
  // if the clicked element has a class named check
  if (event.target.classList.contains('check')) {
    // remove or add the class checked only from this element
    event.target.classList.toggle('checked')
  }
})

This way only the clicked element with check class gets checked class applied.

You can read more about the addEventListener here at MDN .

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