JavaScript’s Document.getElementsByName()
method returns a live NodeList
containing all the elements whose name
attribute matches the specified string.
Syntax
Document.getElementsByName(parameter);
Parameters
A string containing the value of the name
attribute.
Return value
A live NodeList
containing all the elements that have a name
attribute with the specified value. “Live” means that the collection is automatically updated when the underlying document is changed.
Examples
Here is an example of using the JavaScript getElementsByName()
method.
Suppose we have the following HTML elements:
<fieldset>
<legend>Please rate our service:</legend>
<div>
<input type="radio" id="poor" name="rating" value="Poor">
<label for="poor">Poor</label>
</div>
<div>
<input type="radio" id="fair" name="rating" value="Fair">
<label for="fair">Fair</label>
</div>
<div>
<input type="radio" id="good" name="rating" value="Good">
<label for="good">Good</label>
</div>
<div>
<input type="radio" id="veryGood" name="rating" value="Very good">
<label for="veryGood">Very good</label>
</div>
<div>
<input type="radio" id="excellent" name="rating" value="Excellent">
<label for="excellent">Excellent</label>
</div>
</fieldset>
How can we check which radio button is selected, if any, with JavaScript?
We can use the getElementsByName()
method and iterate over the radio buttons:
let ratings = document.getElementsByName('rating');
for (const rating of ratings) {
if (rating.checked) {
console.log(`”${rating.value}” is selected.`);
}
}
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
getElementsByName() |
1 | 12 | 1 | 5 | 5 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |