Home >>Javascript Tutorial >getElementsByName() method

getElementsByName() method

document.getElementsByName() in JavaScript

The document.getElementsByName in JavaScript basically returns all the elements of a specified name.

Here is the syntax of the document.getElementsByName in JavaScript:

document.getElementsByName("name")

Please note that here name is required.

Let's get to understand the document.getElementsByName in JavaScript with an example:

In the following example, the total numbers of genders will get counted with the help of .getElementsByName method.

<script type="text/javascript">  
function totalelements()  
{  
var allgenders=document.getElementsByName("gender");  
alert("Total Genders:"+allgenders.length);  
}  
</script>  
<form>  
Male:<input type="radio" name="gender" value="male">  
Female:<input type="radio" name="gender" value="female">  
<input type="button" onclick="totalelements()" value="Total number of Genders">  
</form>
Output :
Male: Female:  

Let's take another Example:

Click the button to get the tag name of the first element in the document.

<script>
First Name: <input name="fname" type="text" value="PHPTPOINT"><br>
second Name: <input name="fname" type="text" value="TUTORIAL">
<button onclick="myFunction()">click me</button>
<p id="msg"></p>
<script>
function myFunction() {
  var x = document.getElementsByName("fname")[0].tagName;
  document.getElementById("msg").innerHTML = x;
}
</script>
Output :
First Name:
second Name:

 


Popular Tutorials