StackExchange User
StackExchange User

Reputation: 1220

Add class to li if content is a certain string

Would it be possible to add a certain class to a li that contains a certain string of text using JavaScript/jQuery?

UPDATE/NEW QUESTION: Instead of detecting the content of the li, can I have it add the class if the li has another specified class?

Upvotes: 0

Views: 2115

Answers (2)

Geuis
Geuis

Reputation: 42277

Answering the fellow's extended question:

$('li.yourClass').addClass('anotherClass');

You're asking really basic questions. I'd recommend you just spend some time with the beginner jQuery tutorials on the site and you'll understand all of this stuff much better.

Edit: IGNORE MY OLD ANSWER. You learn something every day. Do this, not what I said:

//http://api.jquery.com/contains-selector/
$('li:contains('+ searchText +')').addClass('myClass');

Old answer:

$('li').each(function(){

    var _this = $(this);
    if( _this.text() === testString ){
        _this.addClass('myClass');
    }

});

In the if statement, you can change that to check the .html() of your li or even do a more advanced regex if you need that. But basically, you have to loop through the li's in one form or another to check their content against your testString.

Upvotes: 6

thefrontender
thefrontender

Reputation: 1842

$('li').filter(function () {
    return $(this).text().indexOf('certain string') !== -1;
}).addClass('certainClass');

You can use the jQuery filter function.

The filter function can be passed a selector instead of a function:

$('li').filter('.specified-class').addClass('certainClass');

at which point you should probably just update the initial selector:

$('li.specified-class').addClass('certainClass');

Upvotes: 1

Related Questions