admin管理员组

文章数量:1313006

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?

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?

Share Improve this question edited Aug 27, 2022 at 15:39 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 31, 2012 at 23:58 karaxunakaraxuna 26.9k13 gold badges86 silver badges119 bronze badges 5
  • Yes it is. It's also much easier with a supporting library like jQuery. – Alex Wayne Commented Jan 1, 2013 at 0:00
  • 7 I don't want to use jQuery – karaxuna Commented Jan 1, 2013 at 0:01
  • 1 What is your ultimate goal? Do you need to trigger an event for div1 or modify div1 in some way? – Michael Berkowski Commented Jan 1, 2013 at 0:02
  • try using e.target.parentElement to get div1 – AgnosticDev Commented Jan 1, 2013 at 0:03
  • I'm getting attribute of e.target, depending on that attribute I decide I can do some action or not (div1 has that attribute) – karaxuna Commented Jan 1, 2013 at 0:04
Add a ment  | 

2 Answers 2

Reset to default 5

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/7kYJn/

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

本文标签: javascriptChanging event targetStack Overflow