1

I want to use addEventListener on multiple element with event delegation.

What I want is add click event to .node including dynamic element.

I've tried code below, but target is different when I click .title, .image, or .subtitle.

So is there any way to get .node element ignoring hierarchy?

Thanks 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>
whatAShame
  • 13
  • 2
  • Does this answer your question? [Find the closest ancestor element that has a specific class](https://stackoverflow.com/questions/22119673/find-the-closest-ancestor-element-that-has-a-specific-class) – Hassan Imam Mar 06 '21 at 12:26

1 Answers1

0

If you really want to know whether one of the parent element in your DOM structure is of class node, then you can make use of closest(selector). In the following, we are changing the style of the node if it exists :-

document.querySelector(".nodes").addEventListener("click", function (e) {

  var target = e.target;
  const node = target.closest(".node");
  if (node) {
    node.style.background = 'green';
  }
});
.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>
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39