Moving an element one stage up (or one stage down) in the DOM in vanilla JS

Is there such a “push up” (or “push down”) method to move elements up or down in the DOM?

Theoretical example:

We have a ul with 100 li’s (0-99) and I want li 99 to replace 98 so I “push” it up, and 99 replaces 98 (and the opposite - 98 replaces 99).

I don’t ask it because of a specific problem, I just ask it for general knowledge. I tried to search for such a method and as for know I didn’t find anything in vanilla JS.

Hi @Benos node.replaceChild will probably help you here:

newChild.parentNode.replaceChild(newChild, newChild.previousSibling);
newChild.parentNode.replaceChild(newChild, newChild.nextSibling);

Hope that helps…

My first thought is to simply select each element, then do a temporary copy of their inner content, then switch and set the inner content again to the other’s value.

That technique will switch their values, but won’t move the actual dom element, so that could limit any sliding effects you might have in mind. It will just swap values.

As this is a theoretical question how about a css answer if you just want to change something visually rather than physically?

<meta charset="utf-8">
<title>Untitled Document</title>
ol{	display:flex;flex-wrap:wrap;}
li{flex:1 0  100%}


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.