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

137
Vistas
Javascript closest selector but for sibling

I have this html:

<form action="/action_page.php">

  <label for="qsearch">Qsearch</label>
  <input id="search1" type="search" value="" name="s">
  
  <br>
  <label for="num">Num</label>
  <input type="number" value="" name="Num">
  <br>
  <label for="a">A</label>
  <input type="text" value="" name="a">
  <br>
  <label for="a">B</label>
  <input type="text" value="" name="b">
  
  <input type="submit">
</form>

<script>
console.log( document.getElementById("search1").closest("input[type='text']") );
</script>

I want to get the next text input closest to search input without knowing the ID. But i can't seems to use closest()

What is the correct way to do it using vanilla javascript?

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

0

closest looks up in the DOM. In your case input#search1 is fist element in the DOM. You may try a recursive function like this and check if the element have next sibling. If it has next sibling and matches the type then return it else call the recursive function

function getNextSibling(elem, selector) {
  let sibling = elem.nextElementSibling;
  // check if the element have next sibling
  while (sibling) {
    if (sibling.matches(selector)) {
      return sibling;
    }
    sibling = sibling.nextElementSibling;
  }
};

const x = document.getElementById("search1")
  .nextElementSibling;
console.log(getNextSibling(x, "input[type='text']"))
<form action="/action_page.php">

  <label for="qsearch">Qsearch</label>
  <input id="search1" type="search" value="" name="s">

  <br>
  <label for="num">Num</label>
  <input type="number" value="" name="Num">
  <br>
  <label for="a">A</label>
  <input type="text" value="" name="a">
  <br>
  <label for="a">B</label>
  <input type="text" value="" name="b">

  <input type="submit">
</form>

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