Skip to content
Advertisement

How to select a nested element in pure JavaScript?

This may be a simple thing but I’m struggling on how to target an element on a click event. I got it working with jQuery but I want to do it in pure JavaScript. Basically I have this list:

  <ul class= 'my-todo-list'>
     <li id="todo-1" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
     <li id="todo-2" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
     <li id="todo-3" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
  </ul>

and my JavaScript looks like this:

 document.querySelector('.todo a.delete').addEventListener('click', function(e){
    
    var listElement = this.parentNode.parentElement;
    var todoId = listElement.getAttribute('id').replace('todo-','');
    alert(todoId);
 });

What I want is if I click on a delete link I should see the id for the todo. For example if I click on the second delete link I should alert “todo-2”.

Note: I tried document.querySelector('.todo a.delete') but it didn’t work either.

The easy solution with jQuery is

 $('.todo a.delete').live('click', function(){......})

But I want to do it in pure JavaScript. How can I do that?

Advertisement

Answer

You can add an event listener on the ul element and check if the element that triggered the click event contains the delete class. If it does, get the id attribute from the li element wrapping that particular element which triggered the event

const $ul = document.querySelector('ul');

$ul.addEventListener('click', (e) => {
  if (e.target.matches('a.delete')) {
    const li = e.target.parentElement.parentElement;
    const id = li.getAttribute('id');
    alert(id);
  }
});
<ul>
     <li id="todo-1" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
     <li id="todo-2" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
     <li id="todo-3" class="todo">
            <div class="actions">
                <a href="#" class="edit">Edit</a>
                <a href="#" class="delete">Delete</a>
            </div>
     </li>
  </ul>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement