How come this JQuery loop doesn't change CSS with elements less than 4

Viewed 100

Why doesn't this script loop trough every ul.products element and count li.product element and then change it's css(background to yellow).

When I change < to > then background color changes to all elements. So far I know that the problem is with this script checking every parent elements ul.products but is able to count li.product.

$(document).ready(function() {
  $('ul.products').each(function() {
    if ($('li.product').length < 4) {
      $("li.product").css("background-color", "yellow");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="products">
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
</ul>

<ul class="products">
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
</ul>

https://jsfiddle.net/p9rsuhx3/2/

1 Answers

The issue is because your code looks at all .product elements in the DOM, not specifically those within each ul in the each() loop.

To correct this you can use $(this) to reference the current ul, then retrieve its child li elements:

jQuery($ => {
  $('ul.products').each(function() {
    let $li = $(this).children('.product');
    if ($li.length < 4) {
      $li.css("background-color", "yellow");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul class="products">
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
</ul>

<ul class="products">
  <li class="product">Test</li>
  <li class="product">Test</li>
  <li class="product">Test</li>
</ul>

As an aside, note that jQuery 1.9.1 is very outdated, over 8 years in fact. The latest version, at time of writing this answer, is 3.6.0. I would suggest updating to that.

Related