lundi 4 mai 2020

jQuery: Return list items based on class and position

I am working with unordered lists that are part of a hierarchical menu. I need to return list items based on their class and list position so that I can then make some programmatic css adjustments. Here is some sample HTML:

<ul class="category1">

    <li class="sec secactive" secid="360007912231" categoryid="360002246652" parentsecid="null" style="display: list-item;"><a href="myURL">Section1</a></li>

    <li class="sec subsec" secid="360008584672" categoryid="360002246652" parentsecid="360007912231" style="background-color: red; display: list-item;"><a href="myURL">Subsection A</a></li>

    <li class="sec subsec" secid="360008585372" categoryid="360002246652" parentsecid="360007912231" style="background-color: red; display: list-item;"><a href="myURL">Subsection B</a></li>

    <li class="sec" secid="360007910471" categoryid="360002246652" parentsecid="null" style="display: list-item;"><a href="myURL">Section 2</a></li>

    <li class="sec" secid="360007155641" categoryid="360002246652" parentsecid="null" style="display: list-item;"><a href="myURL">Section 3</a></li>

    <li class="sec subsec" secid="360008585592" categoryid="360002246652" parentsecid="360007912231" style="background-color: red; display: list-item;"><a href="myURL">Subsection A</a></li>

    <li class="sec" secid="360007106191" categoryid="360002246652" parentsecid="null" style="display: list-item;"><a href="myURL">Section 3</a></li>

</ul>

If you look at the sample HTML, you will see that every list item (li) has a class of 'sec'. In most cases a list item will have other class assignments too -- such as 'subsec'. I am trying to put together some jQuery that allows me to programmatically target any 'subsec' list item that immediately precedes a list item that does NOT have the 'subsec' class assignment. So -- if we look again at the sample HTML, I would want to be able to return the 3rd and 6th list items. (They both have a class of 'subsec', and they appear right before another li that does NOT have the 'subsec' class.)

Here is the jQuery I have tried, but it is not working properly. (It seems to be targeting ALL of the 'subsec' list items rather than just the ones I need to return.)

    $("li.subsec").each(function() {
    if ($(this).next('li.sec') !='li.subsec');
    $(this).css("background-color", "red");
    });

Any advice on how to fix my jQuery code would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire