title: How to avoid looping multiple times with dynamically created elements - pure Javascript
body: <p>I'm building a simple to do list using only javascript.
  I know how to achieve the desired result with jQuery.</p>
  <p>I've created a function that puts a line-through as  text-decoration in done tasks.</p>
  <p>For that I'm trying to select the the dynamically added &quot;li&quot; elements with querySelectorAll.
  Then, looping through the selection, I've added an addEventListener whose &quot;click&quot; toggles the line-through effect.</p>
  <p>I'm calling such function every time a new &quot;li&quot; element is added in the todo list.</p>
  <p>Thus, the loop runs and the event is triggered many times, as the number of &quot;li&quot; elements grows in the list.</p>
  <p>If it loops an odd number of times, the objective is &quot;achieved&quot;. But,naturally, running an even number of times it doesn't work.</p>
  <p>Is there a way to solve this situation using a for loop?
  If not, what would be the best practice to achieve the desired result using only pure javascript.</p>
  <pre><code>const arrTask = [];
  
      let insertTask = document.querySelector(&quot;input&quot;);
      insertTask.addEventListener(&quot;keydown&quot;, e =&gt; {
        if(e.keyCode === 13){
          arrTask.push(insertTask.value);
          insertTask.value = &quot;&quot;;
          listTasks()
          e.preventDefault();
        }
      })
      
      const getUlist = document.querySelector(&quot;ul&quot;);
      
      function listTasks(){
        // Add task to the list
          let task = document.createElement(&quot;li&quot;);
          task.innerHTML = `${arrTask[arrTask.length-1]}&lt;button class=&quot;btn btn-danger deletable&quot;&gt;&lt;i class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt;&lt;/button&gt;`
          getUlist.appendChild(task);
          task.classList = &quot;list-group-item list-group-item-action taskContainer d-flex justify-content-between align-items-center&quot;;
          markTasks();
          deleteButton();
      }
      
      function markTasks(){
        // Mark done tasks
        let listItem = document.querySelectorAll(&quot;.taskContainer&quot;);
        for(item of listItem){
          item.addEventListener(&quot;click&quot;, function(){
          this.classList.toggle(&quot;mark&quot;)
          console.log(this)
          })
        }
      }
  </code></pre>
  <p>My code:
  <a href="https://codepen.io/minatogawa/pen/oNbOqXp?editors=0011" rel="nofollow noreferrer">https://codepen.io/minatogawa/pen/oNbOqXp?editors=0011</a></p>