I have following html:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
If mouse is clicked on div2, then e.target is div2. I want target to be div1 in this case. Is it possible?
The simplest way is probably to walk upward up the DOM tree until you find the element you want.
document.addEventListener('mousedown', function(e) {
// start with the element that was clicked.
var parent = e.target;
// loop while a parent exists, and it's not yet what we are looking for.
while (parent && parent.id !== 'div1') {
// We didn't find anything yet, so snag the next parent.
parent = parent.parentElement;
}
// When the loop exits, we either found the element we want,
// or we ran out of parents.
console.log(parent);
});
Example: http://jsfiddle.net/7kYJn/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With