title: How to assign dynamic children a click event listener?
body: <p>I have a parent container with a number of elements, it's not a well defined number of elements, it's generated by using an API once the user starts typing something in an input field. Also these elements are parents to other elements. (I'll give an example below)</p>
  <p>The idea is that once the user clicks that element, I want to display an overlay with more information about that specific element. Sounds good, but the things I've tried didn't work so far.</p>
  <p>I tried to add an event listener onto the container. Consider this basic HTML template.</p>
  <pre><code>&lt;ul&gt;
    &lt;li&gt;&lt;span&gt;Item 1&lt;/span&gt;&lt;span&gt;X&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;Item 2&lt;/span&gt;&lt;span&gt;X&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;Item 3&lt;/span&gt;&lt;span&gt;X&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span&gt;Item 4&lt;/span&gt;&lt;span&gt;X&lt;/span&gt;&lt;/li&gt;
  &lt;/ul&gt;
  
  &lt;form&gt;
    &lt;input type=&quot;text&quot; id=&quot;test&quot;&gt;
  &lt;/form&gt;
  </code></pre>
  <p>So here we have an UL which is the parent element and LI are its children. However, LI are also parents to the span tags that are supposedly showing some vital information so I cannot remove those tags.
  The input field is here just to add something dyamically, to mimik the way my API works.</p>
  <p>So like I said, I have tried to add an event listener on the UL parent &gt;&gt;</p>
  <pre><code>  const items = ul.querySelectorAll('li');
    items.forEach(item =&gt; item.addEventListener('click', function(e) {
    console.log(this);
    }));
  });
  });
  </code></pre>
  <p>Then I tried to add an event listener to each of the items, but instead of logging one item at a time as I click them, it's logging one, two, three and so forth.
  I feel that I'm missing something here and I don't know what it is. Can you guys help me out?</p>
  <p><strong>Later edit</strong>: I found this solution but it doesn't seem very elegant to me and it's prone to bugs if I change stuff later on (like add more children etc).</p>
  <pre><code>ul.addEventListener('click', e =&gt; {
    const items = ul.querySelectorAll('li');
    if(e.target.tagName === 'LI' || e.target.parentElement.tagName === 'LI') {
      if(e.target.tagName === 'LI') {
        e.target.remove();
      } else if(e.target.parentElement.tagName === 'LI') {
        e.target.parentElement.remove();
      }
    }
  });
  </code></pre>