Reputation: 5923
I have a table with some long texts and some short texts. If a <td>
contains a long text I would like to increase the width.
This is what I tried to do:
var text = $('td').text().split('\n');
if(text.length === 1) {
$(this).css('width','270px');
}
jsFiddle
I tried to get the number of line breaks with alert(text.length)
and i get 1. Then if there is 1 line break I added .css('width','270px')
, but doesn't work. What I did wrong?
Thanks for help!
Upvotes: 0
Views: 73
Reputation: 4544
From your fiddle I guess that you cannot use split('\n')
to detect if the text breaks into multiple lines because those line breaks are automatically inserted by the browser for layout purposes and they don't exist as \n
in the text.
I would suggest to compare the rendered height of the cell to calculate the number of lines inside.
UPDATE
Thanks Bill, that was a good point. The cells in each row are always of equal height. The first solution that came to my mind was to use wrapper divs inside the cells. They only expand as much as needed to display the text. It's not "nice" but it seems to do the job: http://jsfiddle.net/dsc4m/7/
Upvotes: 2
Reputation: 32921
I took a stab at what I think you are trying to do:
var $tds = $('td');
$tds.each(function(){
var $td = $(this), length = $.trim($td.text()).length;
if( length > 22 ) {
$td.css('background-color', 'red');
}
});
If not this should get you a lot closer to your goal. Here's an updated fiddle: http://jsfiddle.net/dsc4m/6/
Upvotes: 2