clarkk
clarkk

Reputation: 27685

insertBefore - if element doesnt exists

if the index is larger than the actual number of rows nothing is i appended?

var elm = $('tr', tbl).eq(index);
if(elm){
    row.insertBefore(elm);
}
else{
    row.appendTo(tbl);
}

Upvotes: 3

Views: 752

Answers (2)

user113716
user113716

Reputation: 322492

Since you already have a reference to the table, I'd use its native .rows property to get the DOM element of the row at your index.

Then the simple if( elm ) statement will work.

var elm = tbl[0].rows[index];
if( elm ) {
    row.insertBefore(elm);
}
else{
    row.appendTo(tbl);
}

Requires less code, and will run a little faster.

Upvotes: 0

Emyr
Emyr

Reputation: 2371

if($('tr', tbl).length > index){
    row.insertBefore($('tr', tbl).eq(index));
}
else{
    row.appendTo(tbl);
}

Upvotes: 3

Related Questions