Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a <td> contains "a" then make the <tr> background red but the each() is to slow

How do you write this so it runs faster. It looks like because I'm using an each() it is slowing it down.

Can I use filter()?

 $("#X tr").each(function () {       
     if ($(this).find("table td:eq(1)").text() == "a") {
         $(this).css("background":"red");    
  }

});   

     <table id = "X">
        <tr >
        <td>a</td>
        <td>b</td>
        <td>c</td>
        </tr>
        <tr >
        <td></td>
        <td></td>
        <td></td>
        </tr>
        ...
        <tr >
        <td>a</td>
        <td>b</td>
        <td>c</td>
        </tr>
   </table>

thanks

like image 882
Hello-World Avatar asked Jul 10 '12 13:07

Hello-World


2 Answers

I'd suggest:

$('td:contains("a")').closest('tr').css('background-color','red');

JS Fiddle demo.

Or, in to affect all ancestor tr elements:

$('td:contains("a")').parents('tr').css('background-color','red');

JS Fiddle demo.

Or to affect all tr elements with descendent (however deeply nested):

$('tr').filter(
    function(){
        return $(this).find('td:contains("a")').length;
    }).css('background-color','red');

JS Fiddle demo.

Added a function, lookAt() that might be used instead:

function lookAt(haystack, needle) {
    if (!haystack) {
        return false;
    }
    else {
        needle = needle ? needle : 'a';
        for (var i = 0, len = haystack.childNodes.length; i < len; i++) {
            var cur = haystack.childNodes[i];
            if (cur.nodeType == 3 && cur.nodeValue.indexOf(needle) > -1){
                return true;
            }
            else if (i == (len-1)) {
                return false;
            }
        }
    }
}

$('#table td').filter(
    function() {
        return lookAt(this);
    }).css('background-color', 'red');​

JS Fiddle demo

JS Perf test examining the lookAt() function approach against the return $(this).is(':contains("a")') Sizzle-based approach.

For reference, for a closer comparison the JS Perf jQuery test was the following:

$('#table td').filter(
    function() {
        return $(this).is(':contains("a")')
    }).css('background-color', 'red');​

JS Fiddle demo.

like image 191
David Thomas Avatar answered Sep 30 '22 15:09

David Thomas


You can use the :contains selector: http://jsfiddle.net/Af6Nz/1/.

​$("#X tr:contains('a')").css("background-color", "red");​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
like image 35
pimvdb Avatar answered Sep 30 '22 17:09

pimvdb