InsertBefore - if the item does not exist

if the index is greater than the actual number of rows, am I adding nothing?

var elm = $('tr', tbl).eq(index);
if(elm){
    row.insertBefore(elm);
}
else{
    row.appendTo(tbl);
}
+3
source share
2 answers
if($('tr', tbl).length > index){
    row.insertBefore($('tr', tbl).eq(index));
}
else{
    row.appendTo(tbl);
}
+3
source

Since you already have a reference to table, I would use my own property .rowsto get the DOM element of the string on yours index.

Then a simple operator will work if( elm ).

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

Less code is required and will work a little faster.

0
source

All Articles