私は次のhtmlを持っています:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
div2 でマウスをクリックすると、e.target は div2 になります。この場合、ターゲットをdiv1にしたい。出来ますか?
私は次のhtmlを持っています:
<div id="div1">
<div id="div2">
</div>
</div>
JS:
document.addEventListener('mousedown', function(e){
console.log(e.target);
});
div2 でマウスをクリックすると、e.target は div2 になります。この場合、ターゲットをdiv1にしたい。出来ますか?
おそらく最も簡単な方法は、必要な要素が見つかるまで DOM ツリーを上って行くことです。
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);
});
DOM では、イベント リスナーをアタッチする要素を指定できます。
var div1 = document.getElementById('div1');
div1.addEventListener('mousedown',function(e){
console.log(e.target);
});