skip to Main Content

In jQuery – how can I check to see if a <li> that follows another has a class or not.

Markup is:

<ul>
<li><a href"#">Title 1</a></li>
<li class="LI_sector_child"><a href"#">Title 2</a></li>
<li><a href"#">Title 3</a></li>
<li><a href"#">Title 4</a></li>
</ul>

So, I want to be able to target the 3rd li element as shown above (Title 3) so I can add a class to that.

So, I am looking to find 2 LI’s that are next to each other in the DOM that don’t have the class "LI_sector_child" applied.

Note – I cant use nth-child / nth-of-type as the UL is generated dynamically each time.

2

Answers


  1. This will match an LI that doesn’t have the class, has a following LI, and the following LI also doesn’t have the class. So it selects the first of every pair that don’t have the class.

    $("li:not(.LI_sector_child)").filter(function() {
      return $(this).next('li').length && !$(this).next().hasClass("LI_sector_child");
    }).css("background-color", "yellow");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li><a href "#">Title 1</a></li>
      <li class="LI_sector_child"><a href "#">Title 2</a></li>
      <li><a href "#">Title 3</a></li>
      <li><a href "#">Title 4</a></li>
    </ul>
    Login or Signup to reply.
  2. $(".LI_sector_child").next("li:not('.LI_sector_child')") Find out more about :not() selector, .not() method in the jQuery docs

    $(".LI_sector_child").next("li:not('.LI_sector_child')").addClass("red");
    .red {background: red;}
    <ul>
      <li><a href "#">Title 1</a></li>
      <li class="LI_sector_child"><a href "#">Title 2</a></li>
      <li><a href "#">Title 3</a></li>
      <li><a href "#">Title 4</a></li>
    </ul>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

    Alernatively using the sibling combinator +

    $(".LI_sector_child + li:not('.LI_sector_child')").addClass("red");
    .red {background: red;}
    <ul>
      <li><a href "#">Title 1</a></li>
      <li class="LI_sector_child"><a href "#">Title 2</a></li>
      <li><a href "#">Title 3</a></li>
      <li><a href "#">Title 4</a></li>
    </ul>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search