How to get HTML Elements by Type in Javascript


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:

HTML
<!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>

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);

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);

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 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);

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);

🧪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>
JavaScript
// script.js
function getElementsByType(parentElement, elementType) {
  // > > > 👉 Write code here 👈 < < <
}

const textInputs = getElementsByType(document.body, 'text');
console.log(textInputs);
Please attempt before seeing the Answer:
JavaScript
function getElementsByType(parentElement, elementType) {
  const elements = parentElement.querySelectorAll(
      `input[type="${elementType}"]`
  );
  
  return Array.from(elements);
}

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! 🚀💻

Scroll to Top