How to select elements by name using JavaScript

HTML elements may have the optional name attributes. For example, the following set of radio buttons have the name attributes with the value animal:

<input type="radio" name="animal" value="🦄"> Unicorn
<input type="radio" name="animal" value="🦁"> Lion
<input type="radio" name="animal" value="🦊"> Fox
<input type="radio" name="animal" value="🦌"> Deer

To select the above elements by the name attribute, you can use the getElementsByName() method.

The getElementsByName() method returns a collection of all elements in the document that have the specified name as an HTMLCollection object.

The HTMLCollecton object is an array-like collection of nodes accessible by index numbers.

The following example demonstrates how you can use getElementsByName() to select all radio buttons and return their values as an array:

const buttons = document.getElementsByName('animal')

const animals = Array.from(buttons).map(btn => btn.value)

console.log(animals)

You should see the following output:

["🦄", "🦁", "🦊", "🦌"]

Here is how it works:

  1. First, select all radio buttons by name using the getElementsByName() method.
  2. Then, use Array.from() method to convert the HTMLCollection object into an array. It is necessary because HTMLCollection is not an actual JavaScript array.
  3. Finally, the map() method is used to transform the values of radio buttons into an array.

In HTML5, the name attribute is replaced with the id for many elements. You should consider using the getElementById() method when it is appropriate.

Read this guide to learn more about different ways of getting DOM elements in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.