getElementsByName()
Targeting Form Elements
While IDs and Classes are the most common ways to select HTML elements, there is another attribute specifically used heavily in HTML forms: the name attribute.
You can select these elements using document.getElementsByName().
How it Works
In HTML, multiple elements can share the same name attribute. This is extremely common with radio buttons and checkboxes where multiple inputs belong to the same group.
HTML:
<form>
<input type="radio" name="paymentMethod" value="CreditCard"> Credit Card
<input type="radio" name="paymentMethod" value="PayPal"> PayPal
</form>
JavaScript:
let paymentInputs = document.getElementsByName("paymentMethod");
console.log(paymentInputs.length); // 2
Returning a NodeList
Unlike getElementsByClassName (which returns an HTMLCollection), getElementsByName returns a NodeList.
A NodeList is very similar to an HTMLCollection, but it has one major advantage: modern browsers allow you to use the forEach() array method directly on a NodeList!
let paymentInputs = document.getElementsByName("paymentMethod");
paymentInputs.forEach(input => {
console.log(input.value);
});
// Outputs: "CreditCard", then "PayPal"
💡 Himanshu's Tip:
In modern web development, you won't use getElementsByName very often outside of standard HTML forms. When you move to React, you will likely handle form data using State (useState) rather than selecting DOM elements directly by their name attribute.
Interview Questions
- What kind of collection does
getElementsByName()return? - In what specific HTML scenario is the
nameattribute most commonly used? - What is a key difference between a NodeList and an HTMLCollection when it comes to looping?