If I have a div with multiple elements, is there a way for a click mouse event to give me the index at which the click ocured in that element ? JsFiddle
mainDiv.addEventListener('click', (e)=>{
console.log(e.target)
// Exact index of the click ?
})
#mainDiv{
height: 300px;
width: 300px;
background: #1f2227;
color: white;
white-space: pre-wrap;
}
body{
margin: 0;
}
<div id='mainDiv'>
<span>Some Text</span>
<span>Some Other Text</span>
<span>More text here</span>
</div>
My first though was to use the coordinates of the click event clientX:
, clientY:
and check what element is at that spot on the page, but I'm still not sure how to get the exact location in that element.
The event.target
already gives me the clicked element, can I the exact position in the element too somehow ?
Some text in a span in a div
^ Click occurs there
e.target give me the element clicked, can I get the index ?
Like click occurred on span element at index 3 ?
The only way I can think of is to use the coordinates of the event, but maybe there's some other way.