Simple event delegation example

by benweizhu

HTML

<!DOCTYPE html>
<html>
  
  <head>
    <title>Delegating</title>
  </head>
  
  <body>
    <ul class="ct">
      <li id="first">first</li>
      <li id="second">second</li>
      <li id="third">third</li>
    </ul>
    
    <input type="button" value="Add <li>" />
  </body>
    
</html>

CSS

.ct li {
  margin: 0;
  padding: 3px;
  list-style-type: none;
  background: #ccc;
  color: #666;
}

.ct li:nth-child(2n) {
  background: #333;
  color: #999;
}

JavaScript

document.querySelector('input[type="button"]').addEventListener('click', function() {
  var el = document.createElement('li');
  var id = new Date().getTime().toString();
  el.id = id;
  el.innerHTML = id;
  document.querySelector('.ct').appendChild(el);
});

document.querySelector('body').addEventListener('click', function(event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    alert(event.target.id);
  }
});