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

126
Vistas
Select id closest to id with pure javascript

<div>
  <div id="div2">TEXT</div>
</div>
<div>
  <div id="div2">TEXT</div> <!-- select this -->
</div>

<div id="div1">TEXT</div>

How to select div2 that is closest to div1

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Following w3 docs

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

So make sure your elements id are unique. Can switch to class instead

To select element closet to target element can use Element.closest()

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null

<div id="div-01">Here is div-01
   <div id="div-02">Here is div-02
     <div id="div-03">Here is div-03</div>
   </div>
</div>

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");
// returns the element with the id=div-02
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