Edit Template
  • Home
  • /
  • JS getElementsByName
Edit Template
  • 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 the name attribute you want to target.

  • The result is not an array, but an HTMLCollection (similar to getElementsByClassName()).

Example HTML

				
					<input type="text" name="studentName" />
<input type="text" name="studentName" />
<input type="text" name="studentName" />

				
			

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

ScenarioWhy getElementsByName() Works Well
 Form Groups (Radio, Checkbox, Inputs)Often use the same name to group responses
Bulk Input UpdatesApply changes to multiple fields at once
 Form Validation ScriptsTarget 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.

Scroll to Top