The name
attribute is a staple in HTML, especially within forms. It lets you group related elements—like radio buttons or multiple inputs—under a single identifier. JavaScript can access these elements using document.getElementsByName()
, which returns a live NodeList of all matching elements, making it easy to handle groups in a uniform way.
Using getElementsByName()
allows you to read or update the values, apply style changes, or simply loop through the elements you care about. It works not only for inputs, but for any element with a name
, like textarea
or select
. Let’s explore practical, fun examples of how this method works in different scenarios.
Getting One Element by Name
Sometimes only one element shares a given name
, making it simple to select and modify. Below is a playful example using a magical creature field:
<!DOCTYPE html>
<html>
<head>
<title>Creature Input</title>
</head>
<body>
<input type="text" name="creature" value="Unicorn" />
<script>
// Get the element with name="creature" (first and only match)
const creatureInput = document.getElementsByName('creature')[0];
creatureInput.value = 'Pegasus'; // Change its current value
console.log('Creature changed to:', creatureInput.value);
</script>
</body>
</html>
Here, the input initially lists “Unicorn”, but JavaScript replaces it with “Pegasus”. The console log confirms this update.
Getting Multiple Elements with the Same Name
When several elements share the same name
, such as radio buttons, getElementsByName()
gives you all of them. Let’s build a “favorite pet” selector:
<!DOCTYPE html>
<html>
<head>
<title>Favorite Pet</title>
</head>
<body>
<label><input type="radio" name="pet" value="Cat" />Cat</label>
<label><input type="radio" name="pet" value="Dog" />Dog</label>
<label><input type="radio" name="pet" value="Parrot" />Parrot</label>
<script>
const pets = document.getElementsByName('pet');
// Select the "Dog" option
for (let pet of pets) {
if (pet.value === 'Dog') pet.checked = true;
}
// Find which one is selected now
const selected = Array.from(pets).find(p => p.checked).value;
console.log('Favorite pet:', selected);
</script>
</body>
</html>
We loop through all pet
radio buttons, check “Dog”, then log the selected value.
Changing Properties of All Named Elements
You can also change styles or properties on every element with the same name
. Here’s a charming example with potions:
<!DOCTYPE html>
<html>
<head>
<title>Potion Trinkets</title>
</head>
<body>
<label><input type="checkbox" name="potion" />Invisibility</label>
<label><input type="checkbox" name="potion" />Strength</label>
<label><input type="checkbox" name="potion" />Speed</label>
<script>
const potions = document.getElementsByName('potion');
for (let potion of potions) {
potion.style.outline = '2px dashed purple';
}
console.log('All potion checkboxes outlined');
</script>
</body>
</html>
All potion checkboxes now have a purple dashed outline, adding flair to their appearance.
Working with Named Textareas
The name
attribute is not limited to input fields—it also applies to textarea
elements. Here’s how to access and update one:
<!DOCTYPE html>
<html>
<head>
<title>Feedback Box</title>
</head>
<body>
<textarea name="feedback">Great work!</textarea>
<script>
const feedbackBox = document.getElementsByName('feedback')[0];
feedbackBox.value = 'Fantastic effort!';
console.log('Feedback updated:', feedbackBox.value);
</script>
</body>
</html>
The textarea’s initial message is replaced with something more enthusiastic.
Grouped Form Handling with getElementsByName
To simulate a mini login form, you can access multiple fields by name:
<!DOCTYPE html>
<html>
<head>
<title>Mini Login</title>
</head>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="User" />
<input type="password" name="password" placeholder="Pass" />
<button type="button" id="showBtn">Show Login</button>
</form>
<script>
const username = document.getElementsByName('username')[0];
username.value = 'Edwe';
const password = document.getElementsByName('password')[0];
password.value = 'Code123';
document.getElementById('showBtn').addEventListener('click', () => {
console.log('Username:', username.value);
console.log('Password:', password.value);
});
</script>
</body>
</html>
Filling both fields, clicking the button prints the values to the console.
Inside a Specific Form: Access Named Elements
You can also access named elements scoped to a specific form using form.elements[...]
:
<!DOCTYPE html>
<html>
<head>
<title>Zoo Form</title>
</head>
<body>
<form name="zooForm">
<input type="text" name="animal" value="Elephant" />
</form>
<script>
const zooForm = document.forms['zooForm'];
const animalField = zooForm.elements['animal'];
animalField.value = 'Giraffe';
console.log('Animal updated to:', animalField.value);
</script>
</body>
</html>
The script changes “Elephant” to “Giraffe”, showing scoped selection.
Named Select Dropdowns
The name
attribute also works with select
dropdowns. Here’s a regional picker:
<!DOCTYPE html>
<html>
<head>
<title>Region Selector</title>
</head>
<body>
<select name="region">
<option value="north">Northern Peaks</option>
<option value="south">Southern Sands</option>
</select>
<script>
const region = document.getElementsByName('region')[0];
region.value = 'south';
console.log('Region set to:', region.value);
</script>
</body>
</html>
The dropdown auto-selects “Southern Sands”.
Fun Challenge: Mass Update by Name
Finally, let’s change multiple files at once—all named spell
.
<!DOCTYPE html>
<html>
<head>
<title>Spell List</title>
</head>
<body>
<input type="text" name="spell" value="Invisibility" />
<input type="text" name="spell" value="Levitation" />
<button id="cast">Cast All Spells</button>
<script>
document.getElementById('cast').addEventListener('click', () => {
const spells = document.getElementsByName('spell');
for (let spell of spells) {
spell.value = 'Fireball';
}
});
</script>
</body>
</html>
Clicking “Cast All Spells” changes both inputs to “Fireball”, showing how easily you can update many elements at once.
Conclusion
Through these examples, you’ve used getElementsByName()
and form.elements[name]
to access and update a wide variety of elements—radio buttons, checkboxes, text inputs, textareas, dropdowns—all by name. Each scenario shows how simple it is to grab elements by name and manipulate their values or appearance in creative ways.
References
If you’re curious to explore further or want to double-check what you’ve learned, these trusted documentation pages offer more detailed explanations and examples:
- MDN Web Docs: Document.getElementsByName()
Official Mozilla guide on howgetElementsByName()
works and behaves. - MDN Web Docs: HTMLFormElement.elements
Learn how to access form controls using the.elements
collection. - W3Schools: JavaScript HTML DOM Forms collection
Quick reference on handling forms with JavaScript.