开发者

Reversing order of items in DOMNodeList

开发者 https://www.devze.com 2023-01-18 03:32 出处:网络
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.

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


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)


An alternative to using a documentFragment (which can end up with an unwanted "default:" namespace prefix): clone the NodeList, transfer all the items to the clone, then replace the original node:

function reverseNodeList($nodeList) {
    // clone the original node
    $reverseNodeList = $nodeList->cloneNode();
    // move all nodes off the bottom of the original list onto the new one
    while ($nodeList->lastChild) $reverseNodeList->appendChild($nodeList->lastChild);
    // replace the original node with the new one
    $nodeList->parentNode->replaceChild($reverseNodeList, $nodeList);
}


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)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消