<ul id="my-list">
<li>One</li>
<li>Two <a href="#">A link inside</a></li>
<li>Three</li>
</ul>
JavaScript
var myList = document.getElementById("my-list");
myList.addEventListener("click", function(event) {
event.preventDefault();
console.group("Event fired");
console.log("The event", event);
// "this" references the element that is handling the event (the UL)
console.log("this", this);
// event.currentTarget references the element that is handling the event
// event.currentTarget === this; in this case
this.style.color="#FF9900";
// same as
//event.currentTarget.style.color="#FF9900";
// event.target references the element that triggered the event (the li)
// take note! the "highest" element will source the event
// in this case, the <a> inside the <li> will be the target at times
console.log("event.target", event.target);
// to delegate, we check from where the event came
// and handle it as we please
if (event.target && event.target.nodeName == "LI") {
// List item found! Output the ID!
console.log("List item ", event.target.innerText, " was clicked!");
//event.target.style.color="#FF9900";
}
console.groupEnd();
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.