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
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.
You can use the :contains
selector: http://jsfiddle.net/Af6Nz/1/.
$("#X tr:contains('a')").css("background-color", "red");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With