C# - Understanding getElementById vs getElementsByName

Recently in one of the interviews I was asked what is the difference between document.getelementsbyname and document.getelementbyid in JavaScript? There are following main difference between them :

  • getElementsByName gets elements by their name attribute, getElementById gets the element by its id attribute.
  • There may be many elements on a page with the same name so in this case we use getElementsByName to get list of elements/array but there is (must) only be one element with a given id so in this case we use getelementbyid to get a single element.


document.getelementbyid, getelementbyid document, document.getelementsbyname, how do you get java script, getelementsbyname,   javascript getelementsbyname,getelementsbyname javascript,

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Difference between getelementsbyname & getelementbyid in JavaScript - An Example

    <script type="text/javascript">
    // function to get value by getelementbyid document
    function GetById()
    // function to get value by document.getelementsbyname
    function GetByName()
        var nums= document.getElementsByName("number");
        var result='';
        for(var i=0; i<nums.length; i++)
            result+=nums[i].value +"<br/>";
            document.getElementById("div1").innerHTML= result;

    <form id="form1" runat="server">
        <input type="text" id="num" value="12345" />
        <input type="text" name="number" value="number1" />
        <input type="text" name="number" value="number2" />
        <input type="text" name="number" value="number3" />
    <br />
    <div id="div1" style="border-style: solid; border-width: thin; border-color: inherit;
        width: 625px; height: 100px;">
        Div Section
    <br />
    <input type="button" onclick="GetById();" value="Get Element By Id" />
    <input type="button" onclick="GetByName();" value="Get Element By Name" />

Download the source code click here

Post a Comment