HTML elements may have the optional
name attributes. For example, the following set of radio buttons have the
name attributes with the value
<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 returns a collection of all elements in the document that have the specified name as an
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:
- First, select all radio buttons by name using the
- Then, use
Array.from()method to convert the
HTMLCollectionobject into an array. It is necessary because
- 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.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.