Categories
JavaScript Answers

How to get all input fields inside div with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *