Limit number of Characters in Div with jQuery or CSS

Glenn Glenn's Blog 11 Comments

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">// <![CDATA[
$(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).

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.