tags:

views:

70

answers:

4

Are the values returned by Javascript's getElementsByName(...) guaranteed to be in the same order that they appear in the DOM?

+1  A: 

with getElementsByName(name), the name is required, and thus the name order is irrelevent.

EDIT: I checked the specification and see nothing that would guarantee the order but I have never seen it OUT of order myself.

Spec: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-71555259

Mark Schultheiss
I think you misunderstood my question. I left out the parameter to the function for brevity, but I am interested in the return values from the function. getElementsByName(name) can return multiple elements, if multiple elements have the same name. I am concerned if these elements are going to be in order or not.
denaje
A: 

getElementsByName should return the order of elements in which they were found in the DOM.

jbudge
A: 

If I read the sentence from this which says

"The getElementsByName method works differently in different browsers. In Internet Explorer and Opera, it searches and returns the elements matched by id *and* name attributes. [...]"

I don't think this has to be true, if browsers behave differently. I guess it's the easiest way to add all the elements found to a list and then directly return it. It's rather a reason for efficiency that it's returned in the DOM-order. Actually, I never would rely on it.

Atmocreations
+2  A: 

Since the W3C DOM spec says the following for the similar getElementsbyTagName

getElementsByTagName Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.Blockquote

I can only assume that getElementsByName will also use document order in most implementations.

ninjalj