The JavaScript getElementsByName() method selects HTML elements by their name attribute. It is commonly used with form controls such as text fields, radio buttons, checkboxes, and other elements that share the same name. This tutorial explains its syntax, return value, practical examples, and common mistakes.
What Is getElementsByName() in JavaScript?
getElementsByName() is a method of the Document object. It searches the document for elements whose name attribute exactly matches the supplied string and returns the matching elements in a live NodeList.
Unlike getElementById(), which is designed to find one element by its unique ID, getElementsByName() can return multiple elements. This is useful because several form controls can intentionally share the same name, such as a group of radio buttons.
Syntax of getElementsByName()
document.getElementsByName(name);
Parameter: name is a string containing the exact value of the elements’ name attribute.
Return value: A live NodeList containing all matching elements. If no elements match, the method returns an empty NodeList rather than null.
1. Basic Example of getElementsByName()
In this example, three input elements have the same name. JavaScript selects them and displays how many matching elements were found.
<input type="text" name="username" value="Alex">
<input type="text" name="username" value="Taylor">
<input type="text" name="username" value="Jordan">
<script>
const users = document.getElementsByName("username");
console.log(users.length); // 3
console.log(users[0].value); // Alex
</script>
The returned NodeList is similar to an array for indexed access, so you can read an element with users[0] and check the number of matches with users.length. However, a NodeList is not an Array and does not provide every Array method.
2. Get and Update Input Values
You can loop through the matching elements to read or update their values. The following example changes the value of every input whose name is city.
<input type="text" name="city" value="Dhaka">
<input type="text" name="city" value="Chattogram">
<script>
const cityInputs = document.getElementsByName("city");
for (let i = 0; i < cityInputs.length; i++) {
console.log(cityInputs[i].value);
cityInputs[i].value = "Bangladesh";
}
</script>
For iteration, you can also use forEach() on modern browsers:
document.getElementsByName("city").forEach((input) => {
input.value = "Bangladesh";
});
3. Working with Radio Buttons
Radio buttons in the same group usually share a name. You can use getElementsByName() to find the group and determine which option is selected by checking the checked property.
<label>
<input type="radio" name="gender" value="Male"> Male
</label>
<label>
<input type="radio" name="gender" value="Female"> Female
</label>
<button id="showChoice">Show Selection</button>
<script>
document.getElementById("showChoice").addEventListener("click", () => {
const options = document.getElementsByName("gender");
let selectedValue = "";
for (const option of options) {
if (option.checked) {
selectedValue = option.value;
break;
}
}
console.log(selectedValue || "No option selected");
});
</script>
Only one radio button in a properly configured group can normally be selected at a time. The shared name attribute is what groups the radio controls together.
4. Working with Checkboxes
Checkboxes can also share a name when users are allowed to choose multiple values. Check each element’s checked property to collect the selected options.
<label><input type="checkbox" name="skills" value="HTML"> HTML</label>
<label><input type="checkbox" name="skills" value="CSS"> CSS</label>
<label><input type="checkbox" name="skills" value="JavaScript"> JavaScript</label>
<button id="getSkills">Get Skills</button>
<script>
document.getElementById("getSkills").addEventListener("click", () => {
const checkboxes = document.getElementsByName("skills");
const selectedSkills = [];
for (const checkbox of checkboxes) {
if (checkbox.checked) {
selectedSkills.push(checkbox.value);
}
}
console.log(selectedSkills);
});
</script>
If HTML and JavaScript are connected correctly, the console will contain an array of the selected skill values.
5. Convert the NodeList to an Array
The returned NodeList supports indexed access and iteration, but it is not a true Array. Use Array.from() or the spread syntax when you need Array methods such as map(), filter(), or reduce().
const fields = document.getElementsByName("username");
// Convert NodeList to an Array
const fieldArray = Array.from(fields);
const values = fieldArray.map((field) => field.value);
console.log(values);
You can also use the spread syntax:
const fieldArray = [...document.getElementsByName("username")];
6. Understanding the Live NodeList
The NodeList returned by getElementsByName() is live. This means it reflects matching elements added to or removed from the document after the collection was created.
<input type="text" name="tag" value="First">
<script>
const tags = document.getElementsByName("tag");
console.log(tags.length); // 1
const newInput = document.createElement("input");
newInput.name = "tag";
newInput.value = "Second";
document.body.appendChild(newInput);
console.log(tags.length); // 2
</script>
Because the collection is live, its length can change as the document changes. If you need a fixed snapshot for processing, convert it to an Array with Array.from().
7. getElementsByName() vs. querySelectorAll()
Both methods can return multiple elements, but they work differently. getElementsByName() matches the exact name attribute value and returns a live NodeList. querySelectorAll() accepts any valid CSS selector and returns a static NodeList.
// Find elements by their name attribute
const byName = document.getElementsByName("email");
// Find elements with a CSS attribute selector
const bySelector = document.querySelectorAll('[name="email"]');
Use getElementsByName() when you specifically need elements with a given name. Use querySelectorAll() when you need more flexible CSS selection, such as selecting only text inputs with a particular name.
8. Common Mistakes and Best Practices
- Using an ID instead of a name: This method searches the
nameattribute, not theidattribute. UsegetElementById()for an ID. - Expecting a single element: The method returns a NodeList, even if only one element matches. Access the first match with
elements[0]after checking the length. - Assuming it returns null: No matches produce an empty NodeList. Check
elements.length. - Using an incorrect name: The supplied string must match the name attribute value. Check spelling and capitalization.
- Forgetting that the collection is live: Changes to the document can change the collection. Make an Array copy if you need a stable snapshot.
- Running code too early: Make sure the relevant HTML elements have been parsed before selecting them. Place the script after the markup or use the
DOMContentLoadedevent.
