Select only the most nested list item with specific class

天涯浪子 提交于 2019-12-11 06:06:08

问题


I need to select only the the deepest li.active in the ul structure. In this case that would be Další kategorie. I cannot find css only solution. Is it even possible? Thanks.

<nav class="smenu">
    <ul>
        <li class="predsednictvo first"><a href="/cs/csmg/predsednictvo/"><span>PŘEDSEDNICTVO</span></a></li>
        <li class="sub active komise"><a href="/cs/csmg/komise/"><span>KOMISE</span></a>
            <ul>
                <li class="kategorie first"><a href="/cs/csmg/komise/kategorie/"><span>Kategorie</span></a></li>
                <li class="active dalsi-kategorie last"><a href="/cs/csmg/komise/dalsi-kategorie/"><span>Další kategorie</span></a></li> // I'need to select only this element (current page)
            </ul>
        </li>
        <li class="kontakty"><a href="/cs/csmg/kontakty/"><span>KONTAKTY</span></a></li>
        <li class="reprezentace last"><a href="/cs/csmg/reprezentace/"><span>REPREZENTACE</span></a></li>
    </ul>
</nav>

回答1:


When it is static structure then this selector should do the job:

.smenu > ul > li > ul > li.active {
    /* your rules */
}



回答2:


simply

nav.smenu ul li ul li.active



回答3:


Update: This is currently not possible only via CSS. Children cannot affect thei parents. It will be possible once CSS4 :has() selector gets from working draft to specification and browsers starts implementing it. Current state: https://drafts.csswg.org/selectors-4/#relational


Original answer: Ok, if it's not possible only via CSS, that's how I would do it:

$('li.active:not(:has(li.active))').addClass('deepest');



回答4:


I'm not sure if this was available at the time of the OP, but this works just as well as the accepted answer without the :has operator:

$('.smenu').find('li.active').last().addClass('deepest')

Assuming only one nested path is active at once.



来源:https://stackoverflow.com/questions/17412714/select-only-the-most-nested-list-item-with-specific-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!