shin shin - 10 days ago 6
jQuery Question

How to add a class to `li` element based on a text inside using jQuery

var id
value changes dynamically.
How can I add
class='current'
to the list with the same text. For example when
id=1
,

<li class="current"><a href="http://localhost/myweb/index.php/blog/index">1</a></li>


I tried this but not working.

<ul class='pagination'>
<li>&lt;</li>
<li><a href="http://localhost/myweb/index.php/blog/index">1</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/2">2</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/3">3</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/2">&gt;</a></li>
</ul>

<script>
$(window).load(function() {
var id = 1;
$('.pagination ul li').each(function(){
if($this.val() == id)
{
$this.addClass("current");
}
});

});
</script>

Answer

You had the following three issues

  1. You had the selector as $('.pagination ul li') which is wrong and it should be either $('.pagination li') or $('ul.pagination li')
  2. And you used $this instead of $(this) in two places
  3. Then to compare the value, you should use $(this).find('a').text() instead of $this.val() since you need to find the text inside the anchor tag

Working sample

.current {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='pagination'>
<li></li>
<li><a href="http://localhost/myweb/index.php/blog/index">1</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/2">2</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/3">3</a></li>
<li><a href="http://localhost/myweb/index.php/blog/index/4">4</a></li>
</ul>

<script>
$(window).load(function() {
    var id = 1;
    $('ul.pagination li').each(function(){
        if($(this).find('a').text() == id)
        {
            $(this).addClass("current");
        }
    });

});
</script>