最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Apply CSS if text exceeds a certain length - Stack Overflow

programmeradmin4浏览0评论

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>

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>
Share Improve this question edited Jun 14, 2015 at 12:37 Friedrich 2,3002 gold badges22 silver badges43 bronze badges asked Jun 14, 2015 at 12:33 Adam ScotAdam Scot 1,4094 gold badges26 silver badges43 bronze badges 2
  • What is your expected behaviour by adding class text-exceeds-X-chars? – A. Wolff Commented Jun 14, 2015 at 13:47
  • If none of the answers work or you are still facing trouble, let me know so I can help – AmmarCSE Commented Jun 14, 2015 at 21:04
Add a ment  | 

3 Answers 3

Reset to default 3

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');
    }
});

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

$('.foo').each(function() {
    if ($(this).text().length > x) {
        $(this).addClass('text-exceeds-X-chars');
    }
});
发布评论

评论列表(0)

  1. 暂无评论