# How to select elements by name using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 7, 2020, updated Oct 14, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-select-dom-elements-by-name

> A quick guide to learning how to select DOM elements by name using the JavaScript getElementsByName() method.

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

```html
<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`](https://attacomsian.com/blog/javascript-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](https://attacomsian.com/blog/javascript-arrays):

```javascript
const buttons = document.getElementsByName('animal')

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

console.log(animals)
```

You should see the following output:

```javascript
["?", "?", "?", "?"]
```

Here is how it works:

1. First, select all radio buttons by name using the `getElementsByName()` method.
2. Then, use [`Array.from()`](https://attacomsian.com/blog/javascript-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()`](https://attacomsian.com/blog/javascript-array-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()`](https://attacomsian.com/blog/javascript-select-dom-elements-by-id) method when it is appropriate.

Read [this guide](https://attacomsian.com/blog/getting-dom-elements-javascript) to learn more about different ways of getting DOM elements in JavaScript.
