1

How can I get the td width and make it dynamically change once you added a long text to them... Because I'm planning to have a table-body scrollable.. and I don't want to use the clone() is there way to make it happen?..

Here's the markup:

<div class="table-cont">
<div class="table-header">
    <table>
        <caption>

        </caption>
        <tbody>
            <tr>
                <td>Width 1</td>
                <td>Width 2</td>
                <td>Width 3</td>
                <td>Width 4</td>
                <td>Width 5</td>
                <td>Width 6</td>
            </tr>
        </tbody>
    </table>
</div>
<div class="table-body">
    <table>
        <tbody>
            <tr>
                <td>Width 1</td>
                <td>Width 2</td>
                <td>Width 3</td>
                <td>Width 4</td>
                <td>Width 5</td>
                <td>Width 6</td>
            </tr>
        </tbody>
    </table>
</div>

script:

var tableHeader = $('.table-header').children('table').outerWidth(true);
var tableWidth = $('.table-header table tr td').width();
alert(tableWidth);
$('table-body tr td').append(tableWidth);

css:

.table-header,
.table-body{
border: 1px solid #d3d3d3;
display: inline-block;
}
table {
border-collapse: 0;
border-spacing: 0;
border: 0;
}
table thead th,
table tbody tr td{
border-right: 1px solid #d3d3d3;
padding: 5px 8px;
font-weight: normal;
table-layout: fixed;
}
table thead th:last-child,table tbody tr td:last-child{
border-right: 0;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

1

Try this,

var tableHeader = $('.table-header').children('table').outerWidth(true);
var tableWidth = $('.table-header table tr td').width();
alert(tableWidth);
$('.table-body table tr td').each(function(){
   $(this).append(' '+tableWidth);
});

Fiddle

Updated for making the th with the same width as of td.

$('.table-body table tr th').each(function(){
   $(this).append(' '+tableWidth);
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
1

If you want to set the width use:

$('table-body tr td').width(tableWidth);
Vennik
  • 565
  • 3
  • 11