Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS if text exceeds a certain length

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>
like image 804
Adam Scot Avatar asked Jun 14 '15 12:06

Adam Scot


2 Answers

I'd suggest using the addClass callback function:

$('p.foo').addClass(function() {
    return $.trim(this.textContent).length > 10
           ? 'text-exceeds-X-chars'
           : null;
});
like image 109
undefined Avatar answered Sep 18 '22 10:09

undefined


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');
    }
});
like image 35
AmmarCSE Avatar answered Sep 19 '22 10:09

AmmarCSE