Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

422
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda