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!
Asked
Active
Viewed 1.2k times
2 Answers
23
Code Example:
try {
$li->parentNode->insertBefore( $ul, $li->nextSibling);
} catch(\Exception $e){
$li->parentNode->appendChild( $ul );
}

Layke
- 51,422
- 11
- 85
- 111
-
7Actually, 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(). – marcini Jun 23 '15 at 12:04
-
What if nextSibling is null (i.e. $li is the last in the series)? – IanB Apr 24 '17 at 00:20
-
If `nextSibling` is null, it means `DOMNode::insertBefore` with second parameter omitted. Without second parameter (refnode), newnode is appended to the children. http://php.net/manual/en/domnode.insertbefore.php (Tested and works as the #1 comment & manual said) – nggit Apr 30 '17 at 22:30
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.

Erik Pöhler
- 742
- 2
- 9
- 22