Selecting Elements By Name

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

<input type="radio" name="size" value="S"> S
<input type="radio" name="size" value="M"> M
<input type="radio" name="size" value="L"> L
<input type="radio" name="size" value="XL"> XL
<input type="radio" name="size" value="XXL"> XXLCode language: HTML, XML (xml)

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

The following example uses the getElementsByName() method to select the radio button and returns the list of values:

let elems = document.getElementsByName('size');
let sizes = [].map.call(elems,elem => elem.value);

console.log(sizes);Code language: JavaScript (javascript)

Output:

["S", "M", "L", "XL", "XXL"]Code language: JSON / JSON with Comments (json)

How it works:

  • First, select radio buttons by name using the getElementsByName() method.
  • Then, transform the values of the selected radio buttons to an array. The returned object of the getElementsByName() is a NodeList, which is an array-like object, not an Array object. Therefore, we borrow the map() method of the Array object by using the call() method.
Was this tutorial helpful ?