Sean
Sean

Reputation: 344

Check for certain text and add class

I need to check with jQuery if there is certain text in an LI and add a class accordingly.

Something along these lines...

if ($('ul li:last-child:contains("this text")').length > 0) {
    $(this).addClass("this");
} else if ($('ul li:last-child:contains("that text")').length > 0)
    $(this).addClass("that");
}

Obviously, the code above does not work, but hopefully it's close to what I'm needing. Anyone know how I can write that?

EDIT: Here is the exact code that worked for me thanks to adeneo's answer below...

$('.job-result .job-details ul li:last-child').addClass(function() {
    return $(this).text().indexOf('Augusta') != -1 ? 'augusta' : 
           $(this).text().indexOf('Aiken') != -1 ? 'aiken' :
           $(this).text().indexOf('Job') != -1 ? 'jobshop' : '';
});

Upvotes: 0

Views: 133

Answers (1)

adeneo
adeneo

Reputation: 318372

What you're doing is checking if an element exists by using length, and if it does'nt exist, add a class to that element? That won't work as the element does'nt exist, and inside a conditional like if / else there is no special scope, so this has no meaning?

How about just using an anonymous function inside addClass() to get the scope and check the content :

$('ul li:last-child').addClass(function() {
    return $(this).text().indexOf('this text') != -1 ? 'this' : 
           $(this).text().indexOf('that text') != -1 ? 'that' : '';
});

Upvotes: 5

Related Questions