Skip to content
Advertisement

How to Target Element and Transfer between Lists

I am a newbie here. I have two different lists in HTML: the first list contains several elements, the second list contains none.

My goal is to transfer the elements of list 1 to list 2. I do want to transfer those element clicking on the “move” symbol (which I positioned).

However, I do not know how to target the li element to transfer.

I do know it is a basic question, but still thanks for your support and time !

I have tried to addEventListener to “move”. Therefore, I have tried to use textContext to modify the list 2 elements. However, I do not know how to target the li element in the first list.

//FIRST LIST
<ul class="list-group todos mx-auto text-light">
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <span>play mariokart</span>
            <i class="far fa-trash-alt move"></i>
          </li>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <span>defeat ganon in zelda</span>
            <i class="far fa-trash-alt move"></i>
          </li>

//SECOND LIST
<h1>Items in the Pack</h1>
      <ul class ="pack">
        <li> </li>
        <li> </li>
        <li> </li>
      </ul>

 const list = document.querySelector('.todos');
 const pack = document.querySelector(".pack");


 list.addEventListener('click', e => {

      if(e.target.classList.contains('move')){
       pack.querySelector('li').textContent = `${//missing variable//}%`; 

      }

    }); ```

Advertisement

Answer

You can use parentElement to get the list element which is the immediate parent of the element with the move class.

You can then create new list elements and append them to the destination list. Here’s the flow, with minor changes to your code.

 const list = document.querySelector('.todos');
 const pack = document.querySelector(".pack");

 list.addEventListener('click', e => {
   if (e.target.classList.contains('move')) {
     let originalListEntry = e.target.parentElement;
     var newListEntry = document.createElement("li")
     newListEntry.innerText = originalListEntry.innerText
     pack.appendChild(newListEntry)
   }
 });

Here’s a working example I’ve added a + inside the move span for demo purposes.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement