1

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?

lytabu
  • 75
  • 3

1 Answers1

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>
brk
  • 48,835
  • 10
  • 56
  • 78