Order of DOM NodeList returned by getChildNodes()
Solution 1
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;
}
Solution 2
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.
Solution 3
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.
Adrian Mouat
Software developer Wrote Using Docker for O'Reilly media. Chief Scientist @ Container Solutions http://https://blog.container-solutions.com/author/adrian-mouat @adrianmouat
Updated on June 13, 2022Comments
-
Adrian Mouat almost 2 years
The DOM method
getChildNodes()
returns aNodeList
of the children of the currentNode
. Whilst aNodeList
is ordered, is the list guaranteed to be in document order?For example, given
<a><b/><c/><d/></a>
isa.getChildNodes()
guaranteed to return aNodeList
withb
,c
andd
in that order?The javadoc isn't clear on this.
-
Adrian Mouat over 15 yearsWell, it is different; there's a text node in the middle!
-
Ben over 15 yearsI seem to as well; it's surprising how quickly people jump on these questions here!
-
Adrian Mouat over 15 yearsYes, but no-one has been able to answer it definitively! Let me know if you find that reference.
-
Šime Vidas over 13 yearsI'm curious... Why do you write
null != foo
instead offoo != null
? Is that a Java thing? :) -
jbwharris over 13 years@Šime Vidas I think it's actually a C thing, but with Java's C syntax it seemed wise. The idea is that if you make a typo and write 'null = x' when you meant 'null == x', the compiler will complain. 'x = null' being valid, even in a if test statement. And you should then do the same with the other operators for consistence's sake.
-
Šime Vidas over 13 yearsAha, not a bad idea. Another mechanism is to put your code trough JSLint which will alert on assignments in if headers and other places where assignments are unusual.
-
Adrian Mouat over 13 yearsI don't think you read the question properly. A NodeList is always ordered (regardless of which method returns it). However, is it guaranteed to be in Document order?
-
Tim Büthe about 13 yearsEclipse has a warning for that too. I would prefer writing ´foo == null´ because it's more natural to read.