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');
document.getElementById('mydiv').getElementsByTagName('input')
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.
Try:
var inputs = document.getElementById('mydiv').getElementsByTagName('input');
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With