Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get "clicked" element addEventListener

Tags:

javascript

I know I can grab the element of an individual ID.

Anyway I can attach a listener to the parent div and pass the ID of the individual span that was clicked?

<div id = "divId">
  <span id="one"></span>
  <span id="two"> </span>
 </div>

JS

document.getElementById("two").addEventListener("click", someFunction);
like image 507
Doc Holiday Avatar asked Jun 11 '15 16:06

Doc Holiday


2 Answers

You can use the event object and access its target property

document.getElementById("divId").addEventListener("click", someFunction);

function someFunction(event) {
  console.log(event.target.id);
}
<div id="divId">
  <span id="one">one</span>
  <span id="two"> two</span>
</div>
like image 167
AmmarCSE Avatar answered Nov 11 '22 18:11

AmmarCSE


If the user clicked on a node that was a child of the element the user wanted to test e.target will be a different node. The sensible way to check this nowadays is to listen at the document level and iterate the path (or use some delegation library, of which there are many):

Add one event listener to the document:

const isOnId = (path,id) => path.some(element => element.id === id);

document.addEventListener('click',function(e) {
  if(isOnId(e.path,'two')) {
    //you clicked on or in element with an id two
  } else {
    //you clicked on something else
  }
});
like image 25
Adam Avatar answered Nov 11 '22 18:11

Adam