¿Cuál es la diferencia entre getElementsByName y getElementById en JavaScript?

Recientemente un amigo me preguntaba ¿cuál es la diferencia entre document.getElementsByName y document.getElementById? para los que no saben cuáles son las diferencias entre ellos, a continuación te las presento.


  • getElementsByName obtiene elementos por el atributo de nombre, getElementById obtiene el elemento por su atributo id.
  • Puede haber muchos elementos en una página con el mismo nombre que en este caso usamos getElementsByName para obtener la lista de elementos / matriz, pero debe haber  sólo un elemento con un identificador dado que en este caso usamos getElementById para obtener un solo elemento.

Más temas para aprender Javascript:

¿Cuál es la diferencia entre getElementsByName y getElementById en JavaScript?

¿Cómo eliminar etiquetas HTML de una cadena de texto con JavaScript?

¿Cómo calcular la distancia entre dos puntos en Google Maps con JavaScript?

¿Cómo generar y leer archivos .zip con Javascript?

Cómo obtener la latitud y longitud de un pin que se puede arrastrar a través de Google Maps

Para todos los programadores no hay como un ejemplo práctico, a continuación puedes ver el código fuente.

 <%@ Page Language="Vb" AutoEventWireup="true" CodeFile="Default.aspx.vb" 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
    </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>

 

Artículos relacionados
9 Comentarios
  • Copeland Comentar
    Wednesday, March 7, 2018

    Very energetic article, I loved that bit. Will there be a part 2?

  • Carron Comentar
    Saturday, March 31, 2018

    What's Going down i am new to this, I stumbled upon this I've discovered It positively useful and it has helped me out loads. I hope to give a contribution & assist other users like its helped me. Great job.

  • Hardaway Comentar
    Tuesday, April 10, 2018

    I have checked your website and i've found some duplicate content, that's why you don't rank high in google's search results, but there is a tool that can help you to create 100% unique content, search for: boorfe's tips unlimited content

  • Hendrick Comentar
    Tuesday, April 10, 2018

    I have noticed you don't monetize your website, don't waste your traffic, you can earn additional bucks every month with very good adsense alternative for sites like yours. For more info search in google: blackhatworren's strategies

  • Wymer Comentar
    Tuesday, April 17, 2018

    Com se divertindo tant? conteúd? e artigos você ?á executa em qualquer problemas ?e plagorism ou copyright violação ? Meu site tem um monte de completamente único conteú?o tenho também autoria m? ou terceirizado, m?s aparece m?ito disso é ele aparecendo tudo ?o web ?em meu permissão. Você conhece algum mét??os pa?a ajudar proteger ?ontra conteúdo de ser arrancou ? Eu gostaria realmente agradeç?.

  • Finckh Comentar
    Thursday, April 26, 2018

    catedrático e seus alunos escolhem qualquer história.

  • Rush Comentar
    Saturday, April 28, 2018

    Hurrah! Finally I got a webpage from where I can in fact take useful information concerning my study and knowledge.

  • Crampton Comentar
    Sunday, April 29, 2018

    I don't know if it's just me or if perhaps everybody else encountering problems with your website. It seems like some of the written text within your content are running off the screen. Can somebody else please comment and let me know if this is happening to them too? This could be a issue with my browser because I've had this happen previously. Many thanks

  • Ashcroft Comentar
    Saturday, May 5, 2018

    What's up everyone, it's my first go to see at this site, and paragraph is truly fruitful designed for me, keep up posting such articles.

Enviame un comentario