dubbs
dubbs

Reputation: 1199

jquery check if following LI has class

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.

Upvotes: 1

Views: 23

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

$(".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>

Upvotes: 2

Barmar
Barmar

Reputation: 781004

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>

Upvotes: 2

Related Questions