Welcome to Cactus Juice Sign in | Join | Help

Cameron Scholtz's Blog

Enthusiasm Always Wins
getElementById vs getElementsByName
AJAX...now with Easy Rinse Formula Thanks to DHTML and, more recently AJAX, JavaScript is finally kewl amongst most web developers I know. It's no longer the sole domain of college students skript kiddies and warez sites. Now that the web has grown up a bit so has it's relationship with JS. Frameworks like ASP.NET AJAX make it easy (and free) for even my grandma to include JavaScript with her control oriented, event-driven web applications. Go granny! And personally I find myself using it more often.

So I was trying to get a reference to a group of non-ASP.NET radio buttons. I just wanted to know which radio group I was looking at. The DOM treats all objects with the same name as part of the same group. So if you have two radio buttons with different id or values such as id="Jeff" and id="Jane" but both with name="Persons" then Jeff and Jane are part of the Persons radio button group. (Note: only one button in a group can be selected.)

getElementById is used to return a single element. IDs are unique to a document. A button, text box or div all have an ID property and this ID should always be unique. For example, to reference a div with ID of "doofusDiv"...the JavaScript could look like this:
var doofus = document.getElementById("doofusDiv");
Then you can get at the doofusDiv properties by calling doofus.name, doofus.id, doofus.style, etc.

getElementsByName on the other hand returns a collection. (Caution: the returned elements can appear anywhere in the document.) It is not possible to return elements from a "scope". So make sure the collection returned is unique or you will likely wind up with weird results. In other words if you have a group of radio buttons named "Customer", make sure nothing else on your document is named "Customer".

These methods are two of the workhorses of modern day client scripting. If you're coding DHTML, AJAX, ASP.NET or other client-side work, you'll undoubtedly use them.

Posted: Wednesday, October 25, 2006 5:56 PM by Cameron

Comments

No Comments

Anonymous comments are disabled