Top Ad unit 728 × 90

Latest

random

Difference between document.getElementsByName and document.getElementById in JavaScript

document.getElementById VS document.getElementsByName

In this blog post I will demonstrate frequently asked interview question, what is the difference between document.getElementsByName() and document.getElementById() in JavaScript with example.
  • 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.
JavaScript Example
document.getelementbyid, getelementbyid document, document.getelementsbyname, how do you get java script, getelementsbyname,   javascript getelementsbyname,getelementsbyname javascript,
document.getelementsbyname.value example
<%@ 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">
    <titledocument.getElementById Vs document.getElementsByName </title>

    <script type="text/javascript">   
    // function to get value by getelementbyid document
    function GetById(){        document.getElementById("div1").innerHTML=document.getElementById("num").value;
    }
   
    // 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;
        }
    }   
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <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" />
    </div>
    <br />
    <div id="div1" style="border-style: solid; border-width: thin; border-color: inherit;
        width: 625px; height: 100px;">
        Div Section
    </div>
    <br />
    <input type="button" onclick="GetById();" value="Get Element By Id" />
    <input type="button" onclick="GetByName();" value="Get Element By Name" />
    </form>
</body>
</html>
Difference between document.getElementsByName and document.getElementById in JavaScript Reviewed by Ravi Kumar on 11:52:00 AM Rating: 5

No comments:

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.