karaxuna
karaxuna

Reputation: 26940

Changing event target

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?

Upvotes: 2

Views: 15342

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187312

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/

Upvotes: 5

quandrum
quandrum

Reputation: 1646

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);
});

Upvotes: 1

Related Questions