Get <li> element on click - vanilla JS

Viewed 1427

I have a function that every time the user inserts a value in an input it adds a <li> element inside a <ul>. that same function creates the <li> with the attribute ( onclick="doneToggle" ).

function createListElement() {
    var li = document.createElement("li");
    ul.appendChild(li);
    li.appendChild(document.createTextNode(input.value));
    li.setAttribute("onclick", "doneToggle()")
    li.setAttribute("style", "width: fit-content")
    input.value = "";
}

doneToggle is a function that I want to add a specific class to that element, that css class makes the text have a "line-through" style.

so far this is the function

function doneToggle(element) {
    element.classList.toggle("done");
}

I want that function to retrieve that clicked element and toggle its class without having to assign IDs to the <li>'s. Thank you in advance

2 Answers

Use Element.prototype.addEventListener() instead of onclick. This way the event is automatically passed to the handler function, which allows to access the event.target element that the event was raised on.

Instead of

li.setAttribute("onclick", "doneToggle()")

do

li.addEventListener('click', doneToggle)

Then work with the event passed using event.target which contains the clicked element:

function doneToggle(event) {
    event.target.classList.toggle("done");
}

In an event listener function, this refers to the element that triggered the event, so instead of using element, which is actually and Event Object, use this:

function doneToggle(event) {
    this.classList.toggle("done");
}

And instead of changing the "onclick" attribute, add an event Listener:

function createListElement() {
    var li = document.createElement("li");
    ul.appendChild(li);
    li.appendChild(document.createTextNode(input.value));
    li.addEventListener("click", doneToggle)
    li.setAttribute("style", "width: fit-content")
    input.value = "";
}
Related