Question

I am trying to write an if statement to check if the html of an LI element matches a variable, and if it does, adding a class to that specific li.

My HTML:

<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>

What I've tried so far:

var x = "Three";
if($('li').html() == x) {
  $(this).addClass("active");
}

Desired result:

<li>One</li>
<li>Two</li>
<li class="active">Three</li>
<li>Four</li>
Was it helpful?

Solution

I think you would want to use the filter method:

var x = "Three";
$( "li" ).filter(function( index ) {

   return $(this).html() == x;
}).addClass("active");

OTHER TIPS

You can also use .each()

var x = "Three";
$('li').each(function() {
    if($(this).html() == x) {
        $(this).addClass("active");
    }
});

fiddle

You need to use the filter method :

var x = "Three";
$('li').filter(function(){
    return $.trim(this.innerHTML) == x;
}).addClass('active')

Here is one way -

var x = "Three";
$('li').each(function() {
    if( $(this).is(':contains("' + x + '")')) {
        $(this).addClass('active');
    }
});

Try this

JSFIDDLE

var x = "Three";
$('li').each(function(i,elem){
    if($(elem).text() == x) {
      $(this).addClass("active");
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top