I have a bunch of div elements, all with a specific id. Inside these divs are also divs. Now, if I add an onclick listener to the outermost element, it’s not returning its id. Maybe an example can explain better:
<div id="id1"><div id="bla1"></div></div>
<div id="id2"><div id="bla2"></div></div>
<div id="idn"><div id="blan"></div></div>
document.getElementById("id1").onclick = displayId;
document.getElementById("id2").onclick = displayId;
document.getElementById("idn").onclick = displayId;
function displayId(evt) {
console.log(evt.target.id);
}
If I click on one of the divs now it displays the id of the inner div.
How can I get this to alyways display the id of the outer dviv?
NOTE: The inside div is the same size as the outer.
Use
thisinstead ofevt.targetto refer to the element to which the handler is bound.