Get all Elements by Type using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

banner

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.

index.html
<!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.

index.js
// โœ… 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).

index.js
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.

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

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

index.js
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.

index.js
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().

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee