Reputation: 509
I'm having some weird issue with widths of table cells. All I try to do, is to get the width of the table cell using .width() function, then set that width on the same cell in width attribute:
$table.find('tr:first td').each(function () {
var actualWidth = $(this).width();
$(this).attr("width", actualWidth);
});
Every time I do that, it gets a different width for some cells (Usually reduces one and increase another).
I saw a similar question from 2012: jQuery width() returning incorrect values on table cells But it's quite old and the accepted answer doesn't seem to work.
fiddle: https://jsfiddle.net/awolf/40pj1b2u/
Any help will be appreciated.
Upvotes: 0
Views: 366
Reputation: 1391
I think there are two problems in one. All related to the table-cell display.
The use of border attribute (border="1") in the
<table>
probably messes up the width value when read. Probably the same when setting attr('width') value. In order to match the closest real value, you can use innerWidth() as @Adam P suggested.
Table cells width depends on the full available table width. In your jsfiddle sample, when expanding the table zone, cells' width are increasing. So, from each cell Width, you can compute the global table width, and apply it.
See this https://jsfiddle.net/piiantom/72dvm0v4/, taken from yours, with JS adjustments. Table border can be changed, the JS still works
Upvotes: 1
Reputation: 108
I would consider this a bug. My interpretation: When reading the width, it gets the content-width. When setting it, the box gets rendered and then the border set (taking 1px from content each time). Same with .attr(), .prop(), and .width().
Have a look at box-sizing, .innerWidth() and .outerWidth()!
Upvotes: 0