Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab all child inputs of a specifc div/form using just javascript?

I saw a similar post here, however I want to do something similar using javascript. Basically there a method to grab all user input in some container such as a div or form

<form>
<div>
   <text>
</div>
<div>
  <textarea>
</div>    
 <div>
   <select>
</div>
</form>

An example would be to grab text, textarea, select, and other forms of user input. I saw something like

var elements = document.myform.getElementsByTagName("input")

But it wouldn't work for selects. I know I could possibly just have a duplicate method which attempts to find ("select") but what if the form must keep the order in which user put in information.

EDIT: Thank you for all the responses. Does all the methods mentioned so far only work if the inputs are direct descendants or is there some other method?

like image 611
Qwerty Qwerts Avatar asked Jul 31 '18 17:07

Qwerty Qwerts


1 Answers

You can use a query selector.

document.querySelectorAll('#divID input, #divID select, #divID textarea');
//selects all elements contained by #divId that are input, textarea, or select elements

<div id="myDiv">
<form>
<input type="text">
<select>
<option>1</option>
</select>
<textarea>Text...</textarea>
<div>
 <span>
     <select id="nestedSelect"></select>
 </span>
</div>
</form>
</div>
<script>
var inputs = document.querySelectorAll('#myDiv input, #myDiv select, #myDiv textarea');
for(let i = 0; i < inputs.length; i++){
  console.log(inputs[i]);
}
</script>

You can also get the div or form first and then use querySelectorAll on it to get all the inputs, selects and textareas contained by it (not just direct children).

<div id="myDiv">
<form>
  <input type="text">
  <select>
    <option>1</option>
  </select>
  <textarea>Text...</textarea>
  <div>
  <input type="text"/>
  </div>
  <div>
   <span>
     <select id="nestedSelect">
      <option value="2">2</option>
     </select>
   </span>
  </div>
</form>
</div>
<script>
var divElem = document.getElementById("myDiv");
var inputElements = divElem.querySelectorAll("input, select, textarea");
for(let i = 0; i < inputElements.length; i++){
    console.log(inputElements[i]);
}
</script>
like image 184
Unmitigated Avatar answered Nov 14 '22 23:11

Unmitigated