Reputation: 265
I need set color for TD which containt 1, but only for TH which containt AAA. I have this table and I prepare this script. But script not work. Do you have some idea please ?
Thank very much
TABLE
<TABLE>
<TR><TH COLSPAN="2">AAA</TH></TR>
<TR>
<TD>1</TD>
<TD>2</TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR><TH COLSPAN="2">DDD</TH></TR>
<TR>
<TD>1</TD>
<TD>2</TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
</TABLE>
SCRIPT
$('tr').each(function(){
var tr = $(this);
if (tr.find('th:eq(0)').text()=="AAA") {
if(tr.find('td:eq(0)').text()=="1") tr.addClass('hidden');
}
});
CSS
.hidden{
color:red;
}
Upvotes: 0
Views: 1318
Reputation: 8174
Because of the way your <TH>
s are mixed in with your other rows, the simplest solution involves looping through all rows, like this:
var lastHeader = '';
$('table tr').each(function() {
var cells = $(this).find('td,th');
if (cells.filter('th').size() > 0) { // this is a header row
lastHeader = cells.text();
} else if (lastHeader == 'AAA') { // it's under an AAA section
cells.filter(':contains(1)').addClass('hidden');
}
});
You can see an example of this here: http://jsfiddle.net/kapvr/
I took a bit of a shortcut in the above script to add the class to any cells that contain the text 1
- even if there's more content as well. If you want an exact match, you could modify it like this:
var lastHeader = '';
$('table tr').each(function() {
var cells = $(this).find('td,th');
if (cells.filter('th').size() > 0) { // this is a header row
lastHeader = cells.text();
} else if (lastHeader == 'AAA') { // it's under an AAA section
cells.each(function() {
if ($(this).text() == '1') $(this).addClass('hidden');
});
}
});
That version can be seen in action here: http://jsfiddle.net/5ybPp/
Upvotes: 3
Reputation: 18877
Personally I would change the markup to make this easier.
<TABLE>
<TR><TH COLSPAN="2">AAA</TH></TR>
<TR>
<TD class="hidden">1</TD>
<TD>2</TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR><TH COLSPAN="2">DDD</TH></TR>
<TR>
<TD>1</TD>
<TD>2</TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
</TABLE>
With this altered markup, you don't need the script at all.
How are you getting the HTML in this case?
Upvotes: 0
Reputation:
The body of your each loop looks at a single tr
, trying to find both th
and td
there, but in your HTML the th
and td
are not in the same row. You'll need to look for the th
in tr.prev()
or look for the td
in tr.next()
.
Upvotes: 1