Reversing order of items in DOMNodeList

2019-05-31 18:56发布

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

标签: php dom reverse
3条回答
干净又极端
2楼-- · 2019-05-31 19:22

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)
}
查看更多
Explosion°爆炸
3楼-- · 2019-05-31 19:33

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)

查看更多
放荡不羁爱自由
4楼-- · 2019-05-31 19:33

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);
}
查看更多
登录 后发表回答