Apply CSS if text exceeds a certain length

Is there a way to apply CSS to an element if the text inside the element exceeds a certain length. For example, <p class="foo">123456789</p> .

Then, when the text inside the element exceeds x characters, a new class is applied

 <p class="foo text-exceeds-X-chars">12345678910101010101</p> 
+7
javascript jquery html css html5
source share
3 answers

Use jQuery text () , then use length . If the condition is met, use addClass () to apply the class

 if($('p.foo').text().length > 20){ $('p.foo').addClass('my-class'); } 

If you have multiple p.foo elements, do

 $('p.foo').each(function(){ if($(this).text().length > 20){ $(this).addClass('my-class'); } }); 
+2
source share

I would suggest using the addClass callback function:

 $('p.foo').addClass(function() { return $.trim(this.textContent).length > 10 ? 'text-exceeds-X-chars' : null; }); 
+2
source share

There is no built-in filter or selector for this, so you have to do it manually. The idea is to select all the elements in question and check the length of each of them in a loop:

 $('.foo').each(function() { if ($(this).text().length > x) { $(this).addClass('text-exceeds-X-chars'); } }); 
0
source share

All Articles