Skip to content Skip to sidebar Skip to footer

Get All Input Fields Inside Div (without Js Library)

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');

Solution 1:

document.getElementById('mydiv').getElementsByTagName('input')

Solution 2:

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.

Solution 3:

Try:

var inputs = document.getElementById('mydiv').getElementsByTagName('input');

Solution 4:

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
}

Solution 5:

Post a Comment for "Get All Input Fields Inside Div (without Js Library)"