JavaScript: Search for a string in a row and delete row if string is found
I would like a script that removes every table row for which the keyword STRING is found in a cell, but my script seems to remove every other row开发者_Go百科 that contains the STRING keyword. Apparently, every time a row is deleted the numbering of the rows is updated? How would one account for this? Thanks in advance.
<script type="text/javascript">
var table = document.getElementById("DatePreferred").firstChild;
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var text = row.cells[0].innerText;
if(text.indexOf("STRING")!=-1){
table.deleteRow(i);
}
}
</script>
Edit: So FishBasketGordo's answer got my script to work for IE and Safari but it wasn't working in FF. I looked into where the error was and apparently FF handles .innerText differently. You have to use .textContent instead. So if you add this below to the script above it will use the appropriate method:
if (row.cells[0].textContent){
var text = row.cells[0].textContent;}
else {var text = row.cells[0].innerText;}
When I need to do something like this, I like to work backward:
for(var i= rowCount - 1; i >= 0; i--) {
var row = table.rows[i];
var text = row.cells[0].innerText;
if(text.indexOf("STRING")!=-1){
table.deleteRow(i);
}
}
Just decrement i using i--
when you remove a row, so that your for
loop re-examines the same index (which will now contain the next row).
EDIT: Having looked at your code again, you'll want to compare i
to table.rows.length
rather than your rowCount
variable to account for the changing length of table.rows
.
精彩评论