View Full Version : DOM: How to get a node element from an object id?

06-19-2003, 03:23 PM

I want to make a call like this (instead of document.getElementsByName("ANOTHERID")):


Why can't I make this function call?

When accessing the object like the example below, there is no problem:


How can I get the element from the object I retrieve by using the getElementById function?

06-19-2003, 03:30 PM
getElementsByName indexes objects by their NAME attribute, not their ID - an ID must be unique, but a NAME can be used for multiple elements, hence getElementsByName forms a collection where getElementById is a single object.

06-19-2003, 04:03 PM
Well that's not the problem !

The problem is that I can't make a tag search for specified HTML block using getElementById function.

Maybe I should have written instead document.getElementsByName("ANAME")) of document.getElementsByName("ANOTHERID"))

06-19-2003, 04:04 PM
Maybe I should have written document.getElementsByName("ANAME")) instead of document.getElementsByName("ANOTHERID"))

06-19-2003, 04:14 PM
sorry if I've got the wrong end of the stick, but do you mean you want to select the element on the basis of its tag name? If so, then you want getElementsByTagName instead

06-19-2003, 04:40 PM
not exactly...

I want to get an element by its id (not its tag name) and then perform a getElementsByName on it.

For example if I have this HTML code:

... some HTML code ...
<td id="myid">
<div name="aname">...</div>
<div name="aname">...</div>
<div name="aname">...</div>
... some HTML code ...

Instead of using document.getElementsByName("aname") which is traversing the whole HTML document, I'd like to perform a getElementsByName only in the HTML block contained in the column with id="myid"...

06-19-2003, 04:56 PM
getElementsByName is a method to only the document object.

You could prototype your own in Gecko (et KHTML?), but IE doesn't support the HTMLDom, so you'd need to make a DHTML behavior to get a similar result.

Or, you could just live with it how it is.

06-19-2003, 05:11 PM
While getElementsByTagName is part of the core DOM specification:
getElementsByName is defined only for the HTMLDocument object.

Considering your particular example:
1. Starting HTML 4.01 (maybe earlier) name attribute can not be used with div element (and most elements as well). It was left mostly for backward compatibility with form elements. So you should not be using it like that.
2. You can retrieve the same list of nodes by:
or if you remove all the extra white space within the myid element by simple:

EDIT beetle edited his replay behind by back :mad:

06-19-2003, 06:01 PM
Ok thanks, that was clear!

06-19-2003, 07:53 PM
I'm moving this to the DOM subcategory.