1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How to get HTML Elements by Type in Javascript

ReadTime: 4 minutes

In web development, we often need to precisely select elements based on their type. Lets explore the tools available in Javascript to select elements by their type. 🧑‍💻🎯


Setting the Stage: Initial HTML and JavaScript

Consider a simple HTML snippet containing various input elements:

javascript
<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Element Selection</title>
  </head>
  <body>
      <input type="text" id="username" />
      <input type="password" id="password" />
      <input type="checkbox" id="subscribe" />
      <input type="submit" value="Submit" />

      <script src="script.js"></script>
  </body>
</html>
Sample HTML code to apply approaches described in this blog

Now, let’s dive into the JavaScript world to explore various techniques for capturing these elements.

Using querySelectorAll

Select All Elements with a Specific Type

Here, textInputs will contain all input elements with the type attribute set to “text”. This is particularly useful when you want to target a specific type of input, such as text inputs for usernames.

javascript
// script.js
const textInputs = document.querySelectorAll('input[type="text"]');
console.log(textInputs);
Select all elements with specific type

Broadening the Scope: Get All Input Elements

In this snippet, allInputs encompasses all input elements on the page. While it doesn’t filter by type, it provides a comprehensive list that you can iterate through.

javascript
// script.js
const allInputs = document.querySelectorAll('input');
console.log(allInputs);
get all elements of specific type

Iteratively Processing Elements using forEach

The forEach loop facilitates smooth iteration, enabling actions on each captured element. In this case, we log the id attribute of each text input, showcasing the power of precise iteration.

javascript
// script.js
textInputs.forEach(input => {
  // Perform actions on each text input
  console.log(input.id);
});
Using forEach

Using getElementsByTagName Alternative

For an alternative approach, the traditional getElementsByTagName method captures elements, albeit less versatile than querySelectorAll. It retrieves all elements of the specified tag name, in this case, input.

javascript
// script.js
const elements = Array.from(document.getElementsByTagName('input'));
console.log(elements);
using getElementsByTagName to get all elements with specified tag name

Iterating an HTMLCollection

Converting the obtained HTMLCollection from getElementsByTagName into an array provides greater flexibility for manipulation. This method showcases how to transform the collection into an array for easier handling.

javascript
// script.js
const inputs = document.getElementsByTagName('input');
const elementsArray = Array.from(inputs);
console.log(elementsArray);
iterating HTML collection

🧪Practice Coding Problem: Element Selector by type

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Create a JavaScript function getElementsByType that takes two parameters – an HTML element and a type (e.g., “text”, “checkbox”). The function should return an array of all child elements of the given type.

html
<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Practice</title>
  </head>
  <body>
      <div>
          <input type="text" id="username" />
          <input type="password" id="password" />
          <input type="checkbox" id="subscribe" />
          <input type="submit" value="Submit" />
      </div>

      <script src="script.js"></script>
  </body>
</html>
HTML code

Problem (JavaScript)

javascript
// script.js
function getElementsByType(parentElement, elementType) {
  // > > > 👉 Write code here 👈 < < <
}

const textInputs = getElementsByType(document.body, 'text');
console.log(textInputs);
Javascript Code

Please attempt before seeing the Answer:

Solution
javascript
function getElementsByType(parentElement, elementType) {
const elements = parentElement.querySelectorAll(
    `input[type="${elementType}"]`
);

return Array.from(elements);
}
Solution Code

The function uses querySelectorAll to get all child elements of the specified type within the given parent. The result is converted to an array using Array.from.


Hope this blog will help you grab all the elements as much as you want, whenever you want. Happy grabbing and keep coding! 🚀💻

Contact

Feel free to reach out!