Is there a way to select the grandparent element of a child in Javascript without having to chain the .parentElement method twice? Specifically, I am looking for a method that can substitute .parentElement.parentElement when selecting the desired element, which in this case is parent1
.
The code provided serves as an example to highlight the issue, but my main concern is finding a more efficient way to select elements dynamically introduced into the page. Is there a specific method or technique that could help with this?
Below is the code snippet demonstrating 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>