开发者

jquery: add black border to text of certain length

Using jquery how can one add a bl开发者_开发百科ack border around all "p" elements that surpass a certain value of characters (100)?


Try this:

$("p").filter(function(){
    return $(this).text().length > 100;
}).css("border", "2px solid black");


I think you should probably add a class, rather than including new inline styles. I'll use the callback signature of addClass to achieve this.

I'm going to use the Sizzle text function (available as $.text) because it has markedly better performance than $(this).text().

$('p').addClass(function() {
    return $.text([this]).length > 100 ? 'long' : '';
});

Then simply define a p.long class with whatever styles you want.


Have a look at this fiddle.

It loops through all p elements, and if the content is greater than a given number of characters in length, it applies a style to that element.


Lots of ways to do this: One way:

$('p').filter(function() {
    return $(this).text().length > 100;
}).addClass('biggie');

and the css:

.biggie
{
    border: 2px solid black;
}

Another way:

$('p').filter(function() {
    return $(this).text().length > 100;
}).css({
    'border': '2px solid black'
});

One more way:

$('p').each(function() {
    if ($(this).text().length > 100) $(this).css({
        'border': '2px solid black'
    });
});

another one:

$('p').each(function() {
    if ($(this).text().length > 100) $(this).addClass('biggie');
});

One addition: IF you want different border dependant on the text length, you can also set two classes at once with:

$('p').addClass(function() {
    return $(this).text().length > 100 ? 'long' : 'short';
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜