getElementsByName()
Introduction to JavaScript getElementsByName() method
Every element on an HTML document may have a name
attribute:
Unlike the id
attribute, multiple HTML elements can share the same value
of the name
attribute like this:
To get all elements with a specified name, you use the getElementsByName()
method of the document
object:
The getElementsByName()
accepts a name
which is the value of the name
attribute of elements and returns a live NodeList
of elements.
The return collection of elements is live. It means that the return elements are automatically updated when elements with the same name are inserted and/or removed from the document.
JavaScript getElementsByName() example
The following example shows a radio group that consists of radio buttons that have the same name (rate
).
When you select a radio button and click the submit button, the page will show the selected value such as Very Poor
, Poor
, OK
, Good
, or Very Good
:
How it works:
First, select the submit button by its id
btnRate
using thegetElementById()
method.Second, listen to the click event of the submit button.
Third, get all the radio buttons using the
getElementsByName()
and show the selected value in the output element.
Notice that you will learn about events like click
later. For now, you just need to focus on the getElementsByName()
method.
Summary
The
getElementsByName()
returns a liveNodeList
of elements with a specified name.The
NodeList
is an array-like object, not an array object.
Last updated