Reputation: 7687
I have a table of data which I have previously set the widths of using jquery and the table-layout: fixed
property in CSS. Later on in my code, the contents of the cells may change, possibly necessitating a change in width. The result is something like this fiddle.
As you can see, for long strings, the cell contents flow out of their containing cell and into the next cell over. What I'd like to do is check the contents of a cell after updating it to see if the width of the contents is greater than the cell. In my fiddle, there's a commented out line that does the width updating:
$('.firstItem').width(202) //successfully fits my entry
The problem is that the 202
is hardcoded in, and I don't seem to be able to figure out how to get it. I tried .width()
, .outerWidth()
, and .innerWidth()
on the td
that I'm trying to find the width of the contents of, but to no avail. I know that, if my contents are a span
or something similar, I can call my width methods on that, but most of my contents are just text, and I'd rather not add more DOM elements, since my table is already on the large enough that it can slow things down side.
Is there a good way of getting the width of the text contents of a td
in a table
?
Upvotes: 0
Views: 131
Reputation: 74420
Just set width auto on table:
width: auto;
Or use textWidth snippet:
$.fn.textWidth = function(text){
var org = $(this)
var html = $('<span style="postion:absolute;width:auto;left:-9999px">' + (text || org.html()) + '</span>');
$('body').append(html);
var width = html.width();
html.remove();
return width;
}
$('.firstItem').width($('td.firstItem').textWidth());
Upvotes: 1
Reputation: 5438
You should give your row an id
and then use its scrollWidth
property value and update this css rule to have your scrollWidth as width :
th, td
th, td{
border: 1px solid black;
width: 203px; /* your scrollWidth value here */
height: 20px;
}
Upvotes: 0