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

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.*

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 :)

This entry was posted in JavaScript, Web. Bookmark the permalink.

19 Responses to "The difference between javascript's getElementById() and getElementsByName()"

Leave a reply