I have an html table which is hundreds of rows long that contains a list of strings. I also have an input box that will insert new rows into the table. The second td element in each row is always a string within a div, so a row in the table might look like this:
<tr>
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
</td>
<td class="a_string" style="width:200px;">
<div style="word-wrap:break-word;">hello world</div>
</td>
...
</tr>
I want to insert new rows into this table based on a list of strings from the user, if a string is already in the table it will be ignored and not inserted. The problem arises when the list of strings from the user is very long and the number of rows in the table is very long, the hastily written method i am using to check for duplicates is much too inefficient for this task:
function check_rows(item) { //called on each item in input list
var tf = false;
$('#mytable tbody').children().each(function (i) {
//loop through each tr
if ($('#mytable tbody').children().eq(i).children().eq(1).hasClass('a_string')) {
//if the row is a string to compare (second td element has the class 'a_string')
if (item == $('#mytable tbody').children().eq(i).children().eq(1).children().eq(0).html()) {
//find the string within the div within second td in row "i" (current indexed row)
//compare the strings and if it is found in the table break out of the loop
tf = true;
return false;
}
}
});
//if the item is not found in any of the rows false will be returned
return tf;
}
The function does what it is supposed to do (check for duplicate strings), it is just way too slow. I tried to insert the list without this function and it was almost instantaneous, so the problem is here.
Any suggestions on how to to improve this function would be greatly appreciated!
You can try below code. You don’t have to use
$('#mytable tbody')insideeach. Instead usethis.Try to assign elements to a variable and it will create a reference which will be much faster.