I’d like to dynamically set the background color of a div equal to the background color of the table row that directly proceeded it. Here’s what I think I want to do:
$(this).next().css('background-color', $(this).css('background-color'));
When looking for an answer on this board, I found this thread. This seems to be the answer that worked for them, but mine doesn’t work. Any suggestions gratefully accepted.
EDIT
For those who have asked to see what I’m trying to do, here is the PHP code that is building the body of my table:
<?php
// For every row past the first (header) row, create a table entry
while ( $row = fgetcsv($handle) ) {
echo "<tr class='c_edd_row'>";
// Build each cell
$num = count($row);
for ($c=0; $c < $num; $c++) {
// Do not echo entries 23 through 27 (unused cells)
if ( $c < 23 || $c > 27 ) {
echo "<td>".$row[$c]."</td>";
// save the last entry for the hidden div
$validation_notes = $row[$c];
}
}
echo "</tr>";
echo "<tr class='c_sub_row'>
<td colspan='42' class='c_notes_div'>
<div class='c_notes_div'>".$validation_notes."</div>
</td></tr>";
}
?>
Responders were correct, I didn’t state my problem very well. The divs I was talking about are actually contained in TRs. I’m using this as a dropdown for every row with data in the last row entry.
When I click a row, the following row with class c_sub_row changes from display:none to display:table-row, which works great, but I need it to take the color of the proceeding row when that happens.
FINAL UPDATE – Big thanks to Jonathan Sampson
Here is the final solution, based on the comments below:
$('.c_edd_row').on('click', function(event) {
var bg = $(this).css("background-color");
$(this).next().css("background-color", bg); // colors the next row
$(this).next().find('div').css("background-color", bg); // colors the div
});
Table rows never directly precede
divelements – that would be invalid table markup. If you wanted to set the background of a tr to that of the tr that preceded it, you could do the following:Or perhaps you have a
divwithin atr, and you want thedivto have the same background color as thetrthat precedes the parent of thediv:Where
thisis the currentdivelement.The magic here happens in the anonymous function used as the second argument to the
$.cssmethod. From within it you can do just about anything. For instance, we could pick out any other element on the page and copy its background color:Again, assuming
thisis our targetdivelement, it will now have the same background color as<div class="someOtherDiv">...</div>.Update
From the comments, it sounds like you have two table rows (at least). One visible, and the next one hidden. Within the second one, you have a div. When you click the first (visible) table row, you want to both show the second and apply the bg of the first TR to the DIV within the second (now visible) table-row: