JavaScript document.getElements Method
The `document.getElementsByName()` method returns all elements with the specified name.
The syntax for the `getElementsByName()` method is shown below:
document.getElementsByName(name)
Example of document.getElements Method
In this example, we will count the total number of gender options using the `getElementsByName()` method to retrieve all the gender elements.
<form>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="radio" name="gender" value="Other"> Other
<button onclick="countGenders()">Count Genders</button>
<p id="result"></p>
</form>
JavaScript (script.js):
<script src="script.js">
function countGenders() {
var genders = document.getElementsByName("gender");
var count = genders.length;
document.getElementById("result").innerHTML = "Total number of genders: " + count;
}
</script>
Output:
Total number of genders: 3