Limit number of Characters in Div with jQuery or CSS

A quick snippet for you to limit the number of characters in a span / div etc by a particular value. This function also includes a slightly neater … at the cutoff point:-

<script type="text/javascript">
$(function(){
$(".your-div").each(function(i){
len=$(this).text().length;
if(len>80)
{
$(this).text($(this).text().substr(0,80)+'…');
}
});
});
</script>

Make sure you enter the character value in twice (currently 80).

Update 2019: jQuery Limit number of Characters in Div without Cutting Word

This is an improvement on the code above as it also uses ‘lastIndexOf’ to preserve full words and not cut them short. So for example ‘My sentence ends h…’ becomes ‘My sentence ends here…’ with ‘here’ being the last full word at that particular character count.

<script type="text/javascript">
$(function(){
$(".news-text").each(function () {
len=$(this).text().length;
str= $(this).text().substr(0,80);
lastIndexOf = str.lastIndexOf(" ");
if(len>80) {
$(this).text(str.substr(0, lastIndexOf) + '…');
}
});
});
</script>

Related: jQuery limit number of characters in Input

Here is a neat implementation of jQuery limiting the number of characters in a text input.

See the Pen jquery-practical-exercise-9 by w3resource (@w3resource) on CodePen.0

Limit Number of Characters with CSS

Actually, this can also be done very neatly with the ‘ellipsis’ CSS function, but note that this is relatively new and only works on single lines:-

.your-div {
white-space: nowrap;
width: 150px;
overflow: hidden;
text-overflow: ellipsis;
}

It’s the ‘text-overflow: ellipsis;’ that does all the work, but you do need the other lines for it to work effectively. Then you’ll get the same effect like ‘text stops here …’

About the Author
limit number of characters in div with jquery or css Limit number of Characters in Div with jQuery or CSS 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced Web Designer / Web Developer (Webflow, WordPress, Weebly & Custom), Front-end / Back-end Developer & New Media Specialist, with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries, built up over a number of years.