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
3 Answers
Reset to default 3I'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');
}
});