2

I want to select the parent of the parent of a child in Javascript without chaining the same method twice: child.parentElement.parentElement.Is there a method for this? The element I want to select is parent1.

The code is just to illustrate the problem, but all I want is to know if there is a method that can substitute the .parentElement.parentElement. I need to select it like this because my code is introduced dinamically into the page.

This is the code to illustrate the problem:

const body = document.querySelector('body');

body.querySelector('button').addEventListener('click', function() {
  this.parentElement.parentElement.classList.toggle('black');
});
.parent1 {
  background: yellow;
  padding: 20px;
}

.parent2 {
 background: blue;
 padding: 20px;
}

.black {
 background: black;
}
<div class="parent1">
  <div class="parent2">
    <button>Click</button>
  </div>
</div>
xander17
  • 141
  • 9
  • `document.querySelector('button')` is shorter. Same effect – mplungjan Aug 21 '21 at 14:45
  • 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) – evolutionxbox Aug 21 '21 at 19:37

1 Answers1

4

You can use Element.closest() to find the first parent element that matches a selector, in our case, .parent1:

const body = document.querySelector('body');

body.querySelector('button').addEventListener('click', function() {
  this.closest('.parent1').classList.toggle('black');
});
.parent1 {
  background: yellow;
  padding: 20px;
}

.parent2 {
 background: blue;
 padding: 20px;
}

.black {
 background: black;
}
<div class="parent1">
  <div class="parent2">
    <button>Click</button>
  </div>
</div>
Spectric
  • 30,714
  • 6
  • 20
  • 43