tags:

views:

2932

answers:

5

The DOM method getChildNodes() returns a NodeList of the children of the current Node. Whilst a NodeList is ordered, is the list guaranteed to be in document order?

For example, given <a><b/><c/><d/></a> is a.getChildNodes() guaranteed to return a NodeList with b, c and d in that order?

The javadoc isn't clear on this.

+1  A: 

A document-ordered node list is the behavior in other implementations of the DOM, such as Javascript's or Python's. And a randomly-ordered node list would be utterly useless. I think it's safe to depend on nodes being returned in document order.

John Millikin
+4  A: 

In my experience, yes. The DOM spec isn't any clearer. If you're paranoid, try something like

current = node.firstChild;
while(null != current) {
    ...
    current = current.nextSibling;
}
sblundy
+1  A: 

My experience is that every time that I have bothered to look it has been in document order. However, I believe that I read somewhere it is not guaranteed to be in document order. I can't find where I read that right now, so take it as hearsay. I think your best bet if you must have them in document order would be to use FirstChild then NextSibling until there are no more sibs.

EBGreen
I type way too slow.
EBGreen
I seem to as well; it's surprising how quickly people jump on these questions here!
Calum
Yes, but no-one has been able to answer it definitively!Let me know if you find that reference.
Adrian Mouat
A: 

I'd love to tell you that this is guaranteed (as I believe it is) but the Document Object Model specification itself seems ambiguous in this case. I'm pretty sure that it's always document-order, though.

Calum
A: 
BrewinBombers
Well, it is different; there's a text node in the middle!
Adrian Mouat