I'm trying to make some jquery run on document load so it can grab the color of the background from the div from inside a td cell and put it as the background for the td cell.
Essentially turning the following: https://jsfiddle.net/cyztevwx/ into https://jsfiddle.net/4ocj14rq/1/
<table style="width:100%">
<tr>
<td class="test1" style=""><div style="background-color:#63BE7B;">227.96</div></td>
<td class="test2" style=""><div style="background-color:#F8696B;">227.96</div></td>
<td class="test" style=""><div style="color:blue;">227.96</div></td>
<td class="test1" style="">227.96</td>
<td class="test1" style="color:white;"><div style="background-color:#F8696B;">227.96</div></td>
</tr>
</table>
<button type="button" id="size">Change font size</button>
<table style="width:100%">
<tr>
<td class="test1" style="background-color:#63BE7B;"><div style="background-color:#63BE7B;">227.96</div></td>
<td class="test2" style="background-color:#F8696B;"><div style="background-color:#F8696B;">227.96</div></td>
<td class="test" style=""><div style="color:blue;">227.96</div></td>
<td class="test1" style="">227.96</td>
<td class="test1" style="color:white;background-color:#F8696B;"><div style="background-color:#F8696B;">227.96</div></td>
</tr>
</table>
<button type="button" id="size">Change font size</button>
As you can see some td's allready have a style, some are empty. Some td's have divs and some don't, some td's have styles but not background color.
You can simply achieve this with code:
$(document).ready(function() {
$('td div').each(function() {
$(this).parent('td').css('background-color', $(this).css('background-color'));
});
});
So, we're looping through each div
nested inside a td
, then assigning the background-color
value of the div
to its td
parent. In case a div
doesn't have a background-color
set, the td
will get a rgba(0, 0, 0, 0)
value which would be equivalent to transparent
.
If you don't want a transparent value at all, you can add a condition like so:
$(document).ready(function() {
$('td div').each(function() {
var bgc = $(this).css('background-color');
if(bgc != 'rgba(0, 0, 0, 0)') $(this).parent('td').css('background-color', bgc);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.