17

I am a bit stuck on how to reorder nodes. I am trying to add two simple "move item up" and "move item down" functions. While insertBefore() does what I want to move a sibling before the preceding one, what is the easiest way to move one node down in the DOM? Much appreciated!

0

2 Answers 2

24

Code Example:

 try {
        $li->parentNode->insertBefore( $ul, $li->nextSibling);
 } catch(\Exception $e){
        $li->parentNode->appendChild( $ul );
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Actually, you can do only: $li->parentNode->insertBefore( $ul, $li->nextSibling); The try..catch block is unnecessary, because if $li->nextSibling is null, insertBefore() will act just like appendChild().
What if nextSibling is null (i.e. $li is the last in the series)?
If nextSibling is null, it means DOMNode::insertBefore with second parameter omitted. Without second parameter (refnode), newnode is appended to the children. php.net/manual/en/domnode.insertbefore.php (Tested and works as the #1 comment & manual said)
0

Okay, stupid me. The easy solution is to just go down in the DOM to the nextSibling of the nextSibling and do the same insertBefore... so this is solved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.