Get all Elements by Type using JavaScript


Borislav Hadzhiev

Mon Jan 03 20222 min read


Photo by Chad Madden

Get all Elements by Type using JavaScript #

Use the querySelectorAll() method to get all elements by type, e.g. document.querySelectorAll('input[type="text"]'). The method returns a NodeList containing the elements that match the provided selector.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" /> <input type="number" id="age" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

// ✅ Get all input elements with type = "text" const elements1 = document.querySelectorAll('input[type="text"]'); console.log(elements1); // 👉️ [input#first_name] // ✅ Get all input elements const elements2 = document.querySelectorAll('input'); console.log(elements2); // 👉️ [input#first_name, input#age] // ✅ Get all input elements const elements3 = document.getElementsByTagName('input'); console.log(elements3); // 👉️ [input#first_name, input#age]

In the first example, we used the document.querySelectorAll method to get all input elements that have a type attribute with a value of text.

You can adjust the selector as needed, e.g. the following example selects any type of element with a type attribute set to a value of text (not just input elements).

const elements1 = document.querySelectorAll('[type="text"]');

In the second example, we used the querySelectorAll method to get a NodeList of all of the input tags.

const elements2 = document.querySelectorAll('input');

If you need to iterate over the collection, you can use the forEach() method.

const elements2 = document.querySelectorAll('input'); console.log(elements2); // 👉️ [input#first_name, input#age] elements2.forEach(element => { console.log(element); });

The third example uses the document.getElementsByTagName method to select all input tags.

const elements3 = document.getElementsByTagName('input');
This serves as an alternative for the querySelectorAll method and you might see the getElementsByTagName method used in older code bases.

The method returns an HTMLCollection, which you have to convert to an array if you need to use methods like forEach().

const elements3 = Array.from(document.getElementsByTagName('input')); console.log(elements3); // 👉️ [input#first_name, input#age] elements3.forEach(element => { console.log(element); });

By converting the HTMLCollection to an array, we are able to use any of the array-supported methods.

Use the search field on my Home Page to filter through my more than 1,000 articles.