I think you would want to use the filter method:
var x = "Three";
$( "li" ).filter(function( index ) {
return $(this).html() == x;
}).addClass("active");
Pergunta
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>
Solução
I think you would want to use the filter method:
var x = "Three";
$( "li" ).filter(function( index ) {
return $(this).html() == x;
}).addClass("active");
Outras dicas
You can also use .each()
var x = "Three";
$('li').each(function() {
if($(this).html() == x) {
$(this).addClass("active");
}
});
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
var x = "Three";
$('li').each(function(i,elem){
if($(elem).text() == x) {
$(this).addClass("active");
}
});