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.