Reputation: 377
I'm taking an email and making it readable on the main website. I have no control over the content but need to make it mobile-friendly. I need to change the widths of the table columns to be % rather than px. Tables can be nested. Column count varies, column width varies.
How do I get each TD in the first TR of each table?
$("#emailer table").each(function (index) {
// the table is now a % not px
$(this).width('100%');
// get the column widths
var widths = [];
var row = $(this).children('tr:first');
$(row).first-child.children('td').each(function(){
console.log('td width: '+$(this).width());
widths.push($(this).width;
});
console.log(width_details);
// next steps - add up the widths, convert to % then loop back through and update
});
Edit: table code is created by ckedit so I can rely on things like tbody being present. This is a very cut down version but is fairly typical of the way the content is structured.
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%;">
<tbody>
<tr>
<td style="width:209px">
<p><img alt="" src=""></p>
<p><img alt="" src=""></p>
</td>
<td style="width:3px"> </td>
<td style="width:522px">
<h2><strong>A reminder of the new ...</strong></h2>
<p>We announced just before Christmas that ...</p>
</td>
</tr>
<tr>
<td style="width:209px">
<p><img src=""></p>
</td>
<td style="width:3px"> </td>
<td style="width:522px">
<p><strong>Special 25% price reduction</strong></p>
</td>
</tr>
<tr>
<td colspan="3">
<a href=""><img src=""></a>
</td>
</tr>
<tr>
<td style=" width:209px">
<p><img src=""></p>
</td>
<td style="width:3px"> </td>
<td style="width:522px">
<p>The draft ...</p>
</td>
</tr>
<tr>
<td colspan="3">
<p>
<a href=""></a>
</p>
<table border="0" cellpadding="1" cellspacing="1" style="width:715px">
<tbody>
<tr>
<td colspan="5" style="width:733.13px">
<p><a href="">text</a></p>
</td>
</tr>
<tr>
<td colspan="5" style="width:733.13px">
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="0" cellspacing="0" style="width:728px">
<tbody>
<tr>
<td>
<p><strong>Regular Links</strong></p>
</td>
<td> </td>
<td>
<p><a href="">National Statistics</a></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Upvotes: 0
Views: 395
Reputation: 377
I ended up going with (mostly) vanilla javascript. I'd been totally overthinking the problem.
for (var i = 0; i < tables.length; i += 1) {
var table = tables[i];
var origTableWidth = $(table).width();
$(table).width('100%');
var rowLength = table.rows.length;
for (var j = 0; j < rowLength; j += 1) {
var row = table.rows[j];
var cellLength = row.cells.length;
if (j === 0) {
var width_details = [];
for (var k = 0; k < cellLength; k += 1) {
width_details.push(getNewWidths(row.cells[k]));
}
}
for (var k = 0; k < cellLength; k += 1) {
var cell = row.cells[k];
$(cell).width(width_details[k]);
}
}
}```
Upvotes: 1