How can I use event delegation with addEventListener
on multiple elements?
I want to trigger a click event on .node
, including dynamically added elements.
The code I have tried so far gives different results when clicking on .title
, .image
, or .subtitle
.
Is there a way to target the .node
element regardless of hierarchy?
Thank you in advance :)
document.querySelector(".nodes").addEventListener("click", function (e) {
var target = e.target;
if (target.classList.contains("node")) {
alert("node");
}
});
.node {
width: 100px;
height: 100px;
}
.image {
width: 100px;
height: 100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="nodes">
<div class="node">
<div class="image"></div>
<div class="title">title <span class="subtitle">123</span></div>
</div>
<div class="node">
<div class="image"></div>
<div class="title">title <span class="subtitle">456</span></div>
</div>
</div>
</body>
</html>