views:

28

answers:

1

I am attempting to return columns of text where a column contains certain text.

For example: the text i'm looking for is "02/06/2010".

<table>
    <tr>
        <td>Item Title1</td>
        <td>Item Category</td>
        <td>02/06/2010</td>
    </tr>    
    <tr>
        <td>Item Title2</td>
        <td>Item Category</td>
        <td>02/06/2010</td>
    </tr>
    <tr>
        <td>Item Title3</td>
        <td>Item Category</td>
        <td>10/07/2010</td>
    </tr>
</table>

For every row that contains the text I would like to be able to loop through and use information from the row columns.

I have managed to achieve this (see below) but am unable to access other columns. It is also not efficent and takes 10 seconds or so on a table with 2000 rows.

$('table tr td:nth-child(2) :contains("02/06/2010")');
A: 

Try this instead, it might be quicker:

$('table tr td:nth-child(2)').filter(function() {
    return $(this).text().indexOf('02/06/2010') != -1;
}).closest('tr').css("border", "1px red solid");

Also, since you seem to have a pretty large data set, there's no harm in giving a pure DOM solution a shot, e.g.:

var table = document.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++) {
    var cell = rows[i].getElementsByTagName('td')[2];
    var cellText = cell.childNodes[0];
    if(cellText.data == '02/06/2010') {
        // do something with cell
    }
}

​Try it here: http://jsfiddle.net/ANsUq/

karim79
Thanks for your response. Is it possible to still use the contains method in your first solution. The column may contain a time as well, therefore not always an exact match.
@sirjamescallaghan - I've edited the first solution.
karim79
Works perfectly, much quicker now too! Many thanks.PS. Is there an easier way to access the <td> content. The way I am achieving this at the moment is to use $(this).next('td').text()