Search code examples
javascriptforeachaddeventlistenerappendchild

Appended element disappear after I add a new one, with addEventListener click


I try to add a new span element after the list element when I click on the list item with addEventListener. I managed to add a class, and it works correctly. But when I append the span element to a new list item it disappears and only append at the latest list element.

HTML

<ul>
  <li class="blue">One</li>
  <li class="blue">Two</li>
  <li class="blue">Three</li>
  <li class="blue">Four</li>
  <li class="blue">Five</li>
</ul>

CSS

.blue{
  color: blue;
}
.green{
  color: green;
}

JavaScript

const lis = document.querySelectorAll(".blue");
const span = document.createElement('span');
span.className = 'views';
span.textContent = 0;

lis.forEach(function(list){

  list.addEventListener("click", addGreen);
  function addGreen(e){
    if(list.className.indexOf('green') == -1){
      list.className += ' green';
      list.appendChild(span);
      console.log(e.target); 
    }    
  }     
})

jsfiddle demo


Solution

  • You have only created 1 span element. When you append an existing element it will just move it; you need to create another instance.

    (answered in the comments by @Keith)