Search code examples
javascriptjquerydommove

Move an element one place up or down in the dom tree with javascript


I want a javascript way to move an element one place up or down in the dom tree within a particular known parent using javascript (or jquery is ok), but i want the script to know when an element is the first or last element within the parent and not be moved. for example, if i have the following ...

<div id='parent_div'>
    <div id='div_1'></div>
    <div id='div_2'></div>
    <div id='div_3'></div>
</div>

on click of a button, i want to pass a known id (let's say div_2) and move it up to the position above it, swapping its position with the element that was previously before it (in this case div_1). The ids of the elements don't have to change, and their new position doesn't need to be known, at least not unless they are moved again.


Solution

  • With jQuery:

    var e = $("#div_2");
    // move up:
    e.prev().insertAfter(e);
    // move down:
    e.next().insertBefore(e);