Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut off text inside a div when it reaches a certain # of characters in jQuery?

Tags:

jquery

I know there are lots of truncate scripts out there, but I can't use most of them due to integration issues with the cms I am working on.

Basically I must do it this way:

  1. get a count of the characters inside a div
  2. if count exceeds a certain amount (lets say 10 characters) the text inside the div should be cut off and have "..." appended to the end.

Being terrible at javascript here is my lame non-working attempt:

if ($('div.text').val().length > 10) {

   //     

   ($('div.text').append('...');

}

Can someone please help?

like image 477
James Avatar asked Mar 11 '11 15:03

James


People also ask

How do you cut out text in HTML?

text-overflow: ellipsis; white-space: nowrap; overflow: hidden; in CSS (or hard-code the style, but CSS is cleaner). If you want to completely cut the text off, use clip instead of ellipsis .

How do I show half text in HTML?

The <sup> tag defines superscript text. Superscript text appears half a character above the normal line, and is sometimes rendered in a smaller font.

Can I put text directly in a div?

Yes, you can directly add content text into a div tag, although using p tags would be preferable in most circumstances. Save this answer.

How do I select all text in a div?

To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.


2 Answers

if ($('div.text').text().length > 10)

or

if ($('div.text').html().length > 10)

div elements don't have a "value" as returned by val(), but they do have text or html

and then you probably want to truncate the text like

var text = $('div.text').text();
text = text.substr(0,10) + '...';
$('div.text').text(text);
like image 60
Geoff Avatar answered Oct 10 '22 04:10

Geoff


You're looking for the CSS property text-overflow: ellipsis. This is supported by most browsers (even IE7+), but Firefox only supports it as of version 7. For older browser support, you can use some existing jQuery plugins.

like image 21
wsanville Avatar answered Oct 10 '22 04:10

wsanville