code-guy
code-guy

Reputation: 31

How can I delete specific rows from a table?

I have a table with n number of rows. The value of n changes/updates every minute. The first <td> of every row will either contain some text, or it will be blank. I want to delete/remove all the rows except, the first row and the row whose first cell contains the text 'xyz'. So, how will I be able to do this? This table element is stored in the variable parentTable.

I'm kind of new to javascript and programming. Any help would be appreciated. Thanks.

I tested it with just the second row, but nothing happened even though the text is not xyz in the cell.

if(parentNode.childNodes[1].innerText !== "xyz")
parentTable.deleteRow[1];

And how do I loop around every row and do this?

EDIT: HTML for first cell in every row.

<td class=wbwhite align=center width=40 style="border-top: none; border-left:none; border-right:none;">
&nbsp;
<a href="www.kasdjfkasd.sadsdk.comi" class=pi>xyz</a>
&nbsp;
</td>

Upvotes: 0

Views: 128

Answers (3)

Sharun
Sharun

Reputation: 3082

Try this:

    var table = parentTable;
    var rowCount = table.rows.length;

    for ( var i = 1; i < rowCount; i++ )
    {
        var row = table.rows[i];
        var val=  row.cells[0].childNodes[0].innerHTML.toString();

        if ( 'xyz' != val )
        {
            table.deleteRow( i );

            rowCount--;
            i--;
        }
    }

Upvotes: 1

Yograj Gupta
Yograj Gupta

Reputation: 9869

You can try this

var allRows = parentTable.getElementsByTagName('TR');

for(var i=1; i<allRows.length;)
{
    var tr = allRows[i];
    var firstTd = tr.getElementsByTagName('TD')[0];
    if(firstTd.innerHTML !== 'xyz')
    {
        tr.parentNode.removeChild(tr);
    }else{
        i++;
    }
}

Upvotes: 0

kamituel
kamituel

Reputation: 35950

Use this code (pure JavaScript):

(assuming table has id = tableId).

var all = document.querySelectorAll('#tableId > tbody > tr');

// i = 1 not i = 0 to keep the first row.
for (var i = 1; i < all.length; i++) {
    var td = all[i].querySelectorAll('td')[0];
    if ( td.textContent != "xyz" ) {
        all[i].parentNode.removeChild(all[i]);
    }
}

Upvotes: 0

Related Questions