changing event target

10,179

Solution 1

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/

Solution 2

In DOM, you can specify which element to attach the event listener to:

var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
   console.log(e.target);
});
Share:
10,179
karaxuna
Author by

karaxuna

instanceof Programmer

Updated on June 04, 2022

Comments

  • karaxuna
    karaxuna almost 2 years

    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?