Skip to content
Advertisement

JavaScript insertAfter and insertBefore

I am playing around with the JavaScript functions insertAfter and insertBefore, however I am trying to insertAfter and insertBefore two elements.

For instance, consider the following HTML:

<table>
    <tbody>
        <tr>
            <td>
                Item 1
            </td>
            <td>
                <div class="moveUpDown">
                    <div class="up">
                    </div>
                    <div class="down">
                    </div>
                    <div>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <table>
                    <tr>
                        <td>
                            1
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                Item 2
            </td>
            <td>
                <div class="moveUpDown">
                    <div class="up">
                    </div>
                    <div class="down">
                    </div>
                    <div>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <table>
                    <tr>
                        <td>
                            1
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
</table>

Then I have this JavaScript code snippet:

var row = $(this).parents("tr:first");
if ($(this).is(".up")) {
    row.insertBefore(row.prev());
} else {
    row.insertAfter(row.next());
}

Basically when the Up class is called, the previous row is moved up and when the Down class is called, the current row is moved down one row.

What I want to do, is move the rows Up/Down 2 rows… meaning something like row.prev().prev() or row.next().next() however this does not seem to work.

Is there an easy way around this?

Would appreciate any help/suggestions.

Advertisement

Answer

to go up

row.prev().prev().before(row)

to go down

row.next().next().after(row)

obviously the tr must exist prev/next have to exist

NB you are caching row as the first tr element so row is changing every time the first tr element change

listen to event

$("table").on("click","tr > td > span.moveup", function() {
  var row = $(this).parent().parent();

 if (row.prev().prev().get(0)) row.prev().prev().before(row)

})
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement