Hello
I'm making RSS reader and I'm using DOM.
Now I stuck, trying to reverse the order of the items in the DOMNodeList.
I can make it with 2 cycles - one to make it as array and one for rsort().
Is there any way to reverse the order in the DOMNodeList or must be done with "the array way"?
views:
30answers:
2
A:
Why don't you do it on the client side using javascript? The code for a given node n would be:
function reverse(n) { // Reverses the order of the children of Node n
var f = document.createDocumentFragment( ); // Get an empty DocumentFragment
while(n.lastChild) // Loop backward through the children,
f.appendChild(n.lastChild); // moving each one to the DocumentFragment
n.appendChild(f); // Then move them back (in their new order)
}
Thariama
2010-10-01 09:22:59
+1
A:
There is no method for reversing a DOMNodeList.
But you can keep it as it is, and if you need it, walk through it from the end to the start.
Example:
<?php
$doc=new DOMDocument;
$doc->loadXML('
<div>
<span>1
<span>2
<span>3
</span>
</span>
</span>
</div>');
$nodeList=$doc->getElementsByTagName('span');
for($n=$nodeList->length-1;$n>=0;--$n)
{
echo $nodeList->item($n)->firstChild->data;//returns 321
}
?>
Just point at the end of the NodeList using NodeList->length, then decrement the index and access NodeList->item(index)
Dr.Molle
2010-10-01 09:23:12
How to walk from the end to start ?
T1000
2010-10-01 10:08:45
added example above.
Dr.Molle
2010-10-01 10:37:09
Thank you, that was useful.
T1000
2010-10-01 11:12:38