29

What's the easiest way to get all input fields inside a div without using a javascript library like jQuery? Similar to this jQuery snippet:

var inputs = $('#mydiv :input');
apparat
  • 1,930
  • 2
  • 21
  • 34

6 Answers6

63
document.getElementById('mydiv').getElementsByTagName('input')
Roy Sharon
  • 3,488
  • 4
  • 24
  • 34
20

querySelector and querySelectorAll will fetch the details of what you're expecting easily.

var divElem = document.getElementById("myDiv");
var inputElements = divElem.querySelectorAll("input, select, checkbox, textarea");

It will give all the input, select, textarea elements in array format.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Vishnu Prasanth G
  • 1,133
  • 12
  • 12
  • You don't need "checkbox" - it's an "input" element. Barring that this should be the accepted answer because Roy Sharon's answer doesn't include text areas and select lists. – Rex the Strange Apr 10 '20 at 15:38
13

Try:

var inputs = document.getElementById('mydiv').getElementsByTagName('input');
Andrei Serdeliuc ॐ
  • 5,828
  • 5
  • 39
  • 66
8

If you are on modern browsers (ie9+) you can take advantage of querySelectorAll‎.

var inputs = document.querySelectorAll‎('#myDiv input');

or if you already have the div, you can use it directly

var inputs = myDiv.querySelectorAll('input');
var inputs = myDiv.getElementByTagName('input');

either will work. To serialize you can do this once you have your inputs

var values = {}
for (const input of inputs){
   values[input.name] = input.value
}
Fresheyeball
  • 29,567
  • 20
  • 102
  • 164
3

getElementsByTagName

Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
3
document.getElementById("mydiv").getElementsByTagName("input");
Joe D
  • 3,588
  • 2
  • 19
  • 14