Search code examples
javascripthtmlfunctiontoggleinnerhtml

How can I toggle whole div using JavaScript


I have a done function from which i want to toggle my "temp" div

tasks.innerHTML += `<div id="temp">
        <span id="taskname">
        ${input.value}
        </span>
         
        <button class="done" onclick ="done()"><i class="fa-solid fa-circle-check"></i></button>
        <button class="del" onclick="del(this)"><i class="fa-solid fa-times-circle"></i></button>
        
        </div>`;
function del(e) {
    e.parentNode.remove();      
}

function done() {
    var temp = document.getElementById("temp");
    temp.classList.toggle('completed');      
}

In above code del function is working perfectly but done function is not it only toggles the first div created by innerhtml

To Do List web App

Here if I click check button of Task 3 or Task 4 or Task 2 it will only affect the first div i.e. Task 2 here.

I tried to do it in the similar way I did del() function by using "this"

<button class="done" onclick ="done(this)"><i class="fa-solid fa-circle-check"></i></button>
function done(e) {
    e.classList.toggle('completed');      
}

But it only toggles the particular check button as shown in image To Do List Web App

I want to toggle the whole division of task so that i can strikethrough the text of particular task using css by clicking particular check button.


Solution

  • You just forgot to add parentNode.

    function done(e) {
        e.parentNode.classList.toggle('completed');     
    };
    
    onClick="done(this)"