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.
>Solution :
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>