var ul = document.querySelector("ul"), li = ul.querySelectorAll("li"); /*Bad!! for(var i = 0, len = li.length; i < len; i++){ li[i].onclick = liOnclick; } */ // Good! ul.onclick = function(event){ var node = event.target; liOnclick.call(node); }; function liOnclick(){ if(this.className === "active") this.className = ""; else this.className = "active"; }
Click on any one. Note that instead of attaching event listeners to each of them, I attach an onclick listener to their parent `ul` element, and then delegate this event to the child `li` which was clicked. <ul> <li>List Item</li> <li>List Item</li> <li>List Item</li> <li>List Item</li> <li>List Item</li> <li>List Item</li> </ul>
ul{ width: 300px; height: 100px; } li{ display: inline-block; background: pink; color: white; width: 25%; height: 40%; margin: 10px 10px 0 0; } li.active{ color: green; }