Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading