Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

428
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda