Is there a way to apply a CSS to an element if the text within the element exceeds a certain length. For instance <p class="foo">123456789</p>
.
Then, when the text within the element exceeds x characters a new class is applied
<p class="foo text-exceeds-X-chars">12345678910101010101</p>
I'd suggest using the addClass
callback function:
$('p.foo').addClass(function() {
return $.trim(this.textContent).length > 10
? 'text-exceeds-X-chars'
: null;
});
Use jQuery text(), then, use length
. If the condition is fulfilled, 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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With