How do I change a list item in an unordered list upon a button in that list item being pressed?

The most straightforward way to change the list item is content when a button inside it is clicked is to use event delegation: listen for the click event on the parent <ul>, then use event.target to determine which button was clicked, and finally locate the corresponding <li> through the button is parentElement to modify it.

Implementation Approach

The core is to use the event bubbling mechanism. When the button is clicked, the event bubbles up to the <ul>, and the listener on the <ul>receives the event. In the callback function, event.target points to the actually clicked element (the button) . From there, you can find the <li>that contains the button through parentElement and modify its content.

Code Example

<ul id="myList">
 <li>Item 1 <button class="change-btn">Change</button></li>
 <li>Item 2 <button class="change-btn">Change</button></li>
 <li>Item 3 <button class="change-btn">Change</button></li>
</ul>

<script>
 const list = document.getElementById( myList );

 list.addEventListener( click , function(event) {
   // Only handle clicks on buttons
   if (event.target.classList.contains( change-btn )) {
     // Find the <li> containing the button
     const li = event.target.parentElement;
     // Modify the text content of the list item (keep the button)
     li.firstChild.textContent = Updated! ;
   }
 });
</script>

Key Points

  • Use event delegation: Set the listener on the <ul> instead of adding listeners to each button individually. When list items are added or removed dynamically, event delegation remains effective .
  • event.target vs this: event.target is the actual clicked element (the button), while this (or event.currentTarget) is the <ul> where the listener is bound .
  • If you need to replace the entire <li> content (including the button), you can directly use li.textContent = new content , but this will remove the button. The example above only modifies the text node, preserving the button.
5 Views