For getting elements by type, use the following methods:
- querySelectorAll() method
- getElementsByTagName() method
Let’s check out each of the mentioned methods one by one!
Method 1: Get Element by Type Using querySelectorAll() Method
Follow the given syntax for the getting element by type using the querySelectorAll() method:
Here, the “selector” is the type whose elements you want to get for example “input” or “input[type=text]”. It will find out all the elements matched with the specified selector and return to the DOM. You can pass multiple selectors separated by commas.
Example 1: Get one Element by Type
In the following example, we will create an input field “text” with id “Name” and value “John” and a heading:
Also, create three input type “radio” by assigning ids and values:
Then, create a button by attaching “onclick” event that will trigger the user-defined method named “elementGetbyType()”:
The output displays “John” in alert message which is the value of the input type text field:
Example 2: Get all Elements by Type
Now, get all the elements of the input type by passing “input” as an argument in the “querySelectorAll()” method:
Print the values of the “input” selector including “text” and “radio” on console:
Method 2: Get Element by Type Using getElementsByTagName() Method
Use the following syntax to use the getElementByTagName() method:
Here, “name” is the tagName of an HTML attribute.
In this example, we will get the value of the element by type using the “getElementsByTagName()” method, where we will pass the tag name “input” to get the values of the element to match with the specified tag name and store it in a variable “elementTypeSelector”. Then, define an “elementGetbyType()” function, in which the for loop will iterate until the length of the selector and check the type of the selector; if it is equal to “radio”, then call the alert() method to print the values of the radio element:
The output shows all the values of the input type radio: