Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!