イベントは、親子関係にある子要素のイベントを実行すると、親要素のイベントも実行します。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>sample</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="parent">
<h1>parent</h1>
<div id="child">
<h2>child</h2>
</div>
</div>
</body>
同じイベントリスナを登録した子要素をクリックすると親要素のイベントも実行されます。
script.js
window.onload = function(){
let parent = document.getElementById('parent');
let child = document.getElementById('child');
parent.addEventListener('click', function(){
console.log("parent");
});
child.addEventListener('click', function(){
console.log("child");
});
}
親子関係にある親要素に伝播しないようにするには、「 e.stopPropagation() 」を使います。
window.onload = function(){
let parent = document.getElementById('parent');
let child = document.getElementById('child');
parent.addEventListener('click', function(){
console.log("parent");
});
child.addEventListener('click', function(e){
e.stopPropagation();
console.log("child");
});
}
直前の親要素だけでなく、親子関係がある要素をさかのぼって伝播します。
次のような場合もイベントの伝播が起きます。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>sample</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="grandparent">
<h1>grandparent</h1>
<div id="parent">
<h1>parent</h1>
<div id="child">
<h2>child</h2>
</div>
</div>
</div>
</body>
</html>
script.js
window.onload = function(){
let grandparent = document.getElementById('grandparent');
let child = document.getElementById('child');
grandparent.addEventListener('click', function(){
console.log("grandparent");
});
child.addEventListener('click', function(e){
console.log("child");
});
}
次の場合は、grandparent と child が親子関係にないため、次の場合は、grandparent のイベントは実行されません。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>sample</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="grandparent">
<h1>grandparent</h1>
</div>
<div id="parent">
<h1>parent</h1>
<div id="child">
<h2>child</h2>
</div>
</div>
</body>
</html>