Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

419
Views
Select the parent of the parent of an element

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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!