tengo este 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>Quiero obtener la siguiente entrada de texto más cercana a la entrada de búsqueda sin conocer la ID. Pero parece que no puedo usar el más cercano ()
¿Cuál es la forma correcta de hacerlo usando vainilla javascript?
más cercano mira hacia arriba en el DOM. En su caso input#search1 es el primer elemento en el DOM. Puede probar una función recursiva como esta y verificar si el elemento tiene el siguiente hermano. Si tiene el siguiente hermano y coincide con el tipo, devuélvalo; de lo contrario, llame a la función recursiva
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>