Course contentsShow
← Web Development
Lesson 686 of 2,98212. The Document Object ModelFree lesson

getElementsByName()

Select form elements by their name attribute, primarily used for radio button groups and forms.

getElementsByName()

You'll learn how to select form elements by their name attribute — the go-to method for handling radio buttons and form groups.

What is getElementsByName()?

getElementsByName() is a document method that returns a live NodeList of all elements with a specific name attribute. While it technically works on any element, it's most commonly used with form elements, especially radio button groups where multiple inputs share the same name but represent different choices.

Why Name Attributes Matter

In forms, the name attribute identifies which data field a value belongs to when submitted. Radio buttons in a group all share the same name so only one can be selected at a time. This method lets you grab all those related elements together:

// HTML: <input type="radio" name="size" value="small">
//       <input type="radio" name="size" value="medium">
//       <input type="radio" name="size" value="large">

const sizeOptions = document.getElementsByName('size');
console.log(sizeOptions.length); // 3

Finding the Selected Radio Button

A common pattern is looping through the NodeList to find which radio button is checked:

const sizeOptions = document.getElementsByName('size');

for (let i = 0; i < sizeOptions.length; i++) {
  if (sizeOptions[i].checked) {
    console.log('Selected size:', sizeOptions[i].value);
  }
}

Think of It Like a Roster

Imagine calling attendance for everyone with the last name "Smith" — you're grouping people by a shared identifier. Similarly, getElementsByName() gathers all elements that share the same name, making it perfect for collecting related form controls.

Key Takeaway: Use getElementsByName() to select form elements by their name attribute, especially when working with radio button groups or retrieving form data before submission.