- Home
- /
- JS getElementsByName
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS getElementsByName
JavaScript getElementsByName()
The getElementsByName()
method allows you to select multiple HTML elements that share the same name
attribute. It returns a live HTMLCollection, meaning changes in the DOM are automatically reflected in the result.
Syntax
document.getElementsByName("nameValue");
"nameValue"
is the value of thename
attribute you want to target.The result is not an array, but an
HTMLCollection
(similar togetElementsByClassName()
).
Example HTML
Example JavaScript
let inputs = document.getElementsByName("studentName");
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = `Student ${i + 1}`;
}
This code updates all inputs with the name studentName
and sets their values dynamically.
Best Use Cases
Scenario | Why getElementsByName() Works Well |
---|---|
Form Groups (Radio, Checkbox, Inputs) | Often use the same name to group responses |
Bulk Input Updates | Apply changes to multiple fields at once |
Form Validation Scripts | Target all elements of a group easily |
Things to Keep in Mind
It returns a live HTMLCollection – automatically updates if DOM changes.
The
name
attribute must be identical. It is case-sensitive.Often used with form elements, not general divs or spans.
Summary
getElementsByName()
is ideal for targeting form elements with the same name.Useful in form handling, especially with radio buttons and checkboxes.
Returns a live, indexable list, not a regular array.
Be mindful of case sensitivity and use for form-driven tasks.