views:

30

answers:

2

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"?

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
+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
How to walk from the end to start ?
T1000
added example above.
Dr.Molle
Thank you, that was useful.
T1000