Detect if I click an element inside an element

I have an element (let them say div with id "Test") with a given height and width. Accidentally placed inside this element are other (smaller) elements (let say id "inner1", "inner2", "inner3"), but there are also spaces, spaces in which there are no elements. I would like to have a function that fires when I click on the main element, but then discovers that I press the space bar, or if not, by clicking on the inner element, and if so, return the identifier of the inner element.

Oh, and internal elements are dynamically generated, so I don’t know the identifier before hand, I know that they are either div or spans ... (also as an example, but I will have several types of elements).

Thanks to everyone.

EDIT: (since thanks to Xotic750 for reminding me what I want to say :))

I have not really tried, since I have no idea how to trigger an internal click detection through javascript.

but here is an example:

<div id="test"> <div id="inner1"></div> <span id="inner2"></span> <div id="inner3"></div> </div> <style> div#test { width:300px; height:400px; position:relative; display:block; border:1px solid blue; } div#test div, div#test span { display:block; position:absolute; border:1px solid red; } div#inner1 { top:15px; left:15px; height:15px; width:15px; } span#inner2 { top:65px; left:65px; height:15px; width:15px; } div#inner3 { top:155px; left:155px; height:15px; width:15px; } </style> 

http://jsfiddle.net/BgbRy/2/

+6
source share
2 answers

I think this is what you mean?

 var test = document.getElementById('test'); function whatClicked(evt) { alert(evt.target.id); } test.addEventListener("click", whatClicked, false); 
 div#test { width: 300px; height: 200px; position: relative; display: block; border: 1px solid blue; } div#test div, div#test span { display: block; position: absolute; border: 1px solid red; } div#inner1 { top: 15px; left: 15px; height: 15px; width: 15px; } span#inner2 { top: 65px; left: 65px; height: 15px; width: 15px; } div#inner3 { top: 155px; left: 155px; height: 15px; width: 15px; } 
 <div id="test"> <div id="inner1"></div> <span id="inner2"></span> <div id="inner3"></div> </div> 
+23
source

Add an onClick handler to your test div and use event bubbles to catch clicks on internal elements. You can retrieve a clicked item from an event object.

 document.getElementById("Test").onclick = function(e) { e = e || event var target = e.target || e.srcElement // variable target has your clicked element innerId = target.id; // do your stuff here. alert("Clicked!"); } 
+2
source

Source: https://habr.com/ru/post/947506/