Rob
Rob

Reputation: 451

Using insertBefore() to re-order table rows in javascript

I am trying to shift a table row up on click of a button using JavaScript. The below code is not shifting the row up. The alert statement after the insertBefore statement is also displayed.

function MoveUp(x) {

    var RowLocation = x.id;
    var table = dojo.byId('dynamicTable');
    var rows = table.rows;

    if ((RowLocation > 0) && (RowLocation < (rows.length - 1))) {
        alert('inside if..'+ RowLocation);
        rows.insertBefore(rows[RowLocation],rows[RowLocation-1]);           
        alert('after shift..');
    }
}

Can anyone help to find out the mistake?

Upvotes: 2

Views: 5640

Answers (1)

Wayne
Wayne

Reputation: 60414

You should call insertBefore on the parent of the newly inserted node (instead of table.rows):

var parentNode = rows[RowLocation].parentNode;
parentNode.insertBefore(rows[RowLocation], rows[RowLocation - 1]); 

See here:

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

Use the following to move a row down:

var parentNode = rows[RowLocation].parentNode;
parentNode.insertBefore(rows[RowLocation], rows[RowLocation + 1].nextSibling)

Upvotes: 2

Related Questions