The difference between javascript's getElementById() and getElementsByName()
by Rob Larsen
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
nameattribute 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 byelementName(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, returnsnull. 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
Alan Says:
February 12th, 2008 at 4:30 pm
Excellent info — thank you!
sid Says:
February 29th, 2008 at 1:20 am
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
rob Says:
February 29th, 2008 at 9:30 am
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.
Nicklas Says:
April 8th, 2008 at 8:36 am
getElementById() seems to find element by name attribute as well
thaanaasis Says:
April 23rd, 2008 at 2:46 am
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!
thaanaasis Says:
April 23rd, 2008 at 2:57 am
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 !
rob Says:
April 23rd, 2008 at 6:58 am
you could do something like this:
for (var j=1;j<53;j++) {
var newID = “week_”+j;
document.getElementById[newId].style.backgroundColor=”blue”;
}
Martin Rinehart Says:
July 5th, 2008 at 12:24 pm
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.
clartsonly Says:
September 10th, 2009 at 4:21 am
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])
taneal bhandari Says:
April 14th, 2010 at 11:42 am
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?
taneal bhandari Says:
April 14th, 2010 at 11:43 am
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?
rob Says:
April 14th, 2010 at 11:22 pm
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.
RandyB Says:
May 28th, 2010 at 1:04 am
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.
Ankur Bhutani Says:
June 14th, 2010 at 2:47 am
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
Ankur Bhutani Says:
June 14th, 2010 at 2:50 am
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
rohan sharma Says:
September 10th, 2010 at 5:58 am
thanks ankur bhutani …..
i understand all this…..
Karan kashyap Says:
November 23rd, 2010 at 12:40 pm
really good one ankur bhutani,thanks a lot…………
any other use of getElementsByName plz if u know wanna stuck woth this ….
chandra mohan Says:
January 21st, 2012 at 3:00 pm
thanks all for the information this helps me a lot