1Using the event.target property together with the element.tagName property to find out which element triggered a specified event:
2
3<body onclick="myFunction(event)">
4<p>Click on any elements in this document to find out which element triggered the onclick event.</p>
5<h1>This is a heading</h1>
6<button>This is a button</button>
7<p id="demo"></p>
8
9<script>
10function myFunction(event) {
11 var x = event.target;
12 document.getElementById("demo").innerHTML = "Triggered by a " + x.tagName + " element";
13}
14</script>
1// Make a list
2const ul = document.createElement('ul');
3document.body.appendChild(ul);
4
5const li1 = document.createElement('li');
6const li2 = document.createElement('li');
7ul.appendChild(li1);
8ul.appendChild(li2);
9
10function hide(evt) {
11 // e.target refers to the clicked <li> element
12 // This is different than e.currentTarget, which would refer to the parent <ul> in this context
13 evt.target.style.visibility = 'hidden';
14}
15
16// Attach the listener to the list
17// It will fire when each <li> is clicked
18ul.addEventListener('click', hide, false);
19