Sometimes, we want to get all input fields inside div with JavaScript.
In this article, we’ll look at how to get all input fields inside div with JavaScript.
How to get all input fields inside div with JavaScript?
To get all input fields inside div with JavaScript, we select the container div with querySelector
.
Then we select all the input elements inside with querySelectorAll
.
For instance, we write:
<div>
<input>
<input>
<input>
</div>
to add inputs inside the div.
Then we write:
const divElem = document.querySelector("div");
const inputElements = divElem.querySelectorAll("input, select, checkbox, textarea")
console.log(inputElements)
to select the div with querySelector
.
And then we call divElement.querySelectorAll
with a selector string that selects input, select, checkbox, and textarea elements.
Therefore, inputElements
is a node list with the 3 inputs.
Conclusion
To get all input fields inside div with JavaScript, we select the container div with querySelector
.
Then we select all the input elements inside with querySelectorAll
.