I am working on project and my goal is to toggle each individual li element by clicking toggle button.
I managed to do this so far but it’s working only on first li element.
Can you help me with this code?
<li id="liEl">Target This element</li>
<button id="Btn">toggle</button>
<li id="liEl" >Target This element</li>
<button id="Btn">toggle</button>
<li id="liEl" >Target This element</li>
<button id="Btn">toggle</button>
.done {
text-decoration: line-through;
text-decoration-thickness: 0.2rem;
text-decoration-color:red;
}
Btn= document.getElementById("Btn");
liEl= document.getElementById("liEl");
const toggleDoneClass = () => {
liEl.classList.toggle('done');
};
Btn.addEventListener('click', toggleDoneClass);
3
Answers
id attribute must be unique.
you can use class instead of that.
HTML
You must select all buttons and then add Event Listener to each one by a loop.
Javascript
Now this is Working.
IDs should be unique in a page so maybe switch those to classes.
If you want the buttons you should add them within the list item elements.
You can attach one listener to the
<ul>
element and have that catch events from its children as they "bubble up" the DOM. (This is known as event delegation.)When a click event is fired you can retrieve the specific element that was clicked with event.target, check that it’s a button element, find the
closest
list item element to that button, and then toggle its class.But, ultimately, you don’t really need the buttons.
You are giving the same ids to all the buttons and li instead of id use class names
it will select all the classes which contain buttons
looping all the classes on which you will click it will take that element and then get their previous child which is li and toggle class on that