Rashed Uddin Ripon
Rashed Uddin Ripon

Reputation: 9

jQuery .each function with if condition works for first element

I have HTML content (actually a WordPress plugin's tab like this) -

<div class="store-tabs">
        <ul class="list-inline">
            <li><a href="https://example.com/store/">Products</a></li>
            <li><a href="https://example.com/store/reviews">Reviews</a></li>
        </ul>
</div>

I am trying to add the "Active" class to the link element if I am on the matching URL. My problem is that the condition only works for the first element but the second element does not get the class. Here is my jQuery -

jQuery(document).ready(function($){
  
  var url      = window.location.href;

  $('.store-tabs .list-inline li a').each(function(){

    var current = $(this).attr('href');

    if (current == url) {
      $(this).addClass('active');
    }

   });

});

UPDATE

The code was right but my URLs did not have the matching trailing slash at the end. I have fixed it by adding the slash on the fly (the URLs are auto-generated) -

if(current.slice(current.length - 1) != '/') {
      current = current + '/';
    }

Thanks, everyone :)

Upvotes: 0

Views: 132

Answers (1)

Alina Shtanko
Alina Shtanko

Reputation: 21

https://example.com/store/reviews is not equal to https://example.com/store/reviews/. Try to add '/' to the end of your href="https://example.com/store/reviews"

Upvotes: 1

Related Questions