bernte
bernte

Reputation: 1184

Remove table row by finding content with clause

I have this code:

<table>
    <tbody>
        <tr><td>Table 1</td></tr>
    </tbody>
</table>

<table>
    <tbody>
        <tr>
            <td align="left">Number</td>
            <td><b>33</b></td>     
        </tr>
        <tr>        
            <td width="150" align="left">Field</td>
            <td>XXXX</td>
        </tr>
        <tr>    
            <td align="left">Select: </td>
            <td colspan="4">
                <select name="status" size="1">
                    <option selected="selected" value="2">one</option>
                    <option value="1">two</option>
                </select>                   
            </td>
        </tr>
    </tbody>
</table>

and i want to remove this line by searching "Field" with pure Javascript:

    <tr>
        <td width="150" align="left">Field</td>
        <td>XXXX</td>
    </tr>

when there is a 33, 66 or 99 in this line from my 2nd table:

    <tr>
        <td align="left">Number</td>
        <td>33</td>     
    </tr>

The problem is that i don't have any id's or classes for identification! i want to use the code with Greasemonkey.


Here you can see a JSFIDDLE of my table.
And here you can see on JSFIDDLE how it should look.

Best regards bernte

Upvotes: 1

Views: 103

Answers (1)

Juan Jimenez
Juan Jimenez

Reputation: 5892

Here you go:

var disallowedValues = ['33', '66', '99'];    
var cols = document.getElementsByTagName('td');
var colslen = cols.length;
var i = -1;
var disallowedTable;

while(++i < colslen){
    // look for the td where the disallowed values are
    if(disallowedValues.indexOf(cols[i].innerHTML) >= 0)
    {
        // get the table where the disallowed values is
        disallowedTable = cols[i].parentNode.parentNode.parentNode;
        // break the cicle to stop looking for other rows
        //break;
    }
}

// look for the 'Field' value only on the table that has the disallowed value
var cols = disallowedTable.getElementsByTagName('td');
cols = disallowedTable.getElementsByTagName('td');
colslen = cols.length;
i = -1;

while(++i < colslen){
    // look for the td where the 'Field' value is
    if(cols[i].innerHTML == 'Field')
    {
       // get the tr for such td
        var deletionTR = cols[i].parentNode;       
        //delete that tr
        deletionTR.parentNode.removeChild(deletionTR);
        // break the cicle to stop looking for other rows
        break;
    }
}

You can always do a simpler version if jquery is an option.

Upvotes: 1

Related Questions