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

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

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 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