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>