The difference between javascript's getElementById() and getElementsByName()

The above question is one I’ve gotten in my logs a couple of times. I don’t actually answer it anywhere on the site, so I figured I might as well answer it here. For some strange reason, in my mellowed old age, I’m all about helping and I haven’t written about web technologies in about a month, so it can’t hurt.

The basic answer is this-

  • getElementById() is incredibly useful. If you write any JavaScript at all, you’ll likely use it all the time
  • getElementsByName() isn’t really useful at all. I’ve never used it ever and can’t really think of a place where I would use it. I rarely use the name attribute and can’t really see where I would want to use it in any way that would make sense in the context of this method.

To define them, the specs say

getElementsByName
With HTML 4.01 documents, this method returns the (possibly empty) collection of elements whose name value is given by elementName (The name attribute value for an element.) In [XHTML 1.0] documents, this methods only return the (possibly empty) collection of form controls with matching name. This method is case sensitive.

Which is to say you pass the method a string (the name) and you get back a nodeList , a collection of elements with matching that name.

Which is, as far as my experience goes, a big pile of useless.*

getElementById
Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.

Which means- pass this method a string (the id) and this method will return either an element matching that id or null. This is probably one of the most used DOM methods in the Javascript universe. Accessing and manipulating elements is what JavaScript is all about and getElementById is the handiest method for accessing an individual element on a page.

*which isn’t to say I don’t want to hear about a really cool use of it if there’s one out there. If you’ve got one, please share! I love seeing interesting code samples 🙂

19 thoughts on “The difference between javascript's getElementById() and getElementsByName()

  1. what about is you have multiple groups of check boxes and would like to select / deselect each group

    I see this function being useful there.

    Sid

  2. That’s a perfect example. Thanks.

    I actually ended up using this myself after writing this article. I was interfacing with a form created by some Java code and the only identifier was a name attribute.

  3. Hello!

    In the following code, I came up with a small technicality. Somewhere I have a php function which aims to create 52 buttons, one for each week of the year.
    ———————————
    <?php function calendar_week($start_week,$counter) {
    for ($i=$start_week;$i<$counter+$start_week;$i++)
    {
    echo “”;
    }
    }
    ?>
    —————————————-

    On another part of the code, I use a javascript function that tries to get the previous 52 buttons and change the buttons’ color:
    —————————————-
    function …{

    for (var j=1;j<53;j++) {
    document.getElementById[“week_j”].style.backgroundColor=”blue”;
    }

    }
    —————————————-

    The problem is that I haven’t found yet a way to reference “week_j”, in order to avoid writing the same line 52 times (i.e. document.getElementById[“week_(1 to 52)”].style.backgroundColor=”blue”;

    Thank you all in advance!

  4. Sorry for the (annoying) multiple postings, but what is wrong with php commands???

    I cannot paste my one line code, so I’ll try to attach pseudo-code instead:

    td (start) newline

    input type (equals) button
    name (equals) calendar(underscore)week(underscore)(dollarsign)i
    id (equals) week(underscore)i
    newline

    td (end) newline

    Thanks !

  5. you could do something like this:

    for (var j=1;j<53;j++) {
    var newID = "week_"+j;
    document.getElementById[newId].style.backgroundColor="blue";
    }

  6. Don’t go dissin’ my good buddy getElementsByName(). Give him some love.

    Notice the singular, getElementById(), and the plural, getElementsByName(). Since you must give radio buttons a common name, getElementsByName is the way to go to get the whole group.

  7. getElementsByName is incredibly useful, I am just about to use it now to discover which of my 1800 checkboxes are checked, so I can find the .value of each checked one in order to generate n quotations based on the vehicles selected.

    it beats the old fashioned way of using .all([name])

  8. I can’t get getElementsByName() to work. Here’s the HTML button on my page:

    I want to hide this button in situations and tried this:

    document.getElementsByName(“btn_clr_case_id_c”).style.display = ‘none’;

    But that doesn’t work. Any thoughts why?

  9. I can’t get getElementsByName() to work. Here’s the HTML button on my page:
    input type=”button” name=”btn_clr_case_id_c” tabindex=”0″ title=”Clear [Alt+C]” accessKey=”C” class=”button” onclick=”this.form.case_id_c.value = ”; this.form.proc_id1_c.value = ”;” value=”Clear”

    I want to hide this button in situations and tried this:

    document.getElementsByName(“btn_clr_case_id_c”).style.display = ‘none’;

    But that doesn’t work. Any thoughts why?

  10. getElementsByName returns a nodeList, so you need to reference the specific member of the collection.

    document.getElementsByName(“btn_clr_case_id_c”)[0].style.display = ‘none’; //references the first one.

  11. I’m new to JavaScript, but here’s a good reason to use getElementsByName. Assuming that you use the “id” value to uniquely identify each element on the page, you may want to get an array of a group of elements. For example, if you have dynamically created a list of buttons, you may not know how many will actually be on the page. You’ve dynamically named them button1, button2, etc. By giving them each the same name value of “dynaButts”, you can put them all into an array by calling $myArray = getElementsByName(“dynaButts”). I think that’s pretty useful.

  12. getelementByid is used when we are going to implement code of html to javascript(i.e when implementing client side validation )
    getelemntbyname is used when we are going to implement validation or check xode of html to any server side language like php,jsp or asp.net

  13. example below code is used to delete selected check boxes

    function valDelForm()

    {
    frmCheckform = document.form1;

    var chks = document.getElementsByName(‘checkname[]’);

    var hasChecked = false;

    // Get the checkbox array length and iterate it to see if any of them is selected

    for (var i = 0; i < chks.length; i++)
    {
    if (chks[i].checked)

    {
    hasChecked = true;
    break;
    }
    }
    }
    and checkboxes are created dynamiclly using for loop so in this case we will use getementby name

  14. really good one ankur bhutani,thanks a lot…………
    any other use of getElementsByName plz if u know wanna stuck woth this ….

Leave a Reply

Your email address will not be published. Required fields are marked *