• How to target specific parent div using jQuery

    Take this HTML for example:

    <ul class="wrap">
     <li class="out"></li>
     <li class="out"></li>
     <li class="out">
         <ul class="wrap">
            <li class="out"></li>
            <li class="out"></li>
         </ul>
     </li>
    </ul>
    

    Using jQuery, what is the best way to target a list item that had a "wrap" class but is not a child of a nested ul? Alternatively, how can I mark li with the class "wrap" that is nested in ul, which is nested in li?

    +3
    source share
    4 answers

    For non-nested li, you have two options:

    $('ul.wrap:has(ul) > li') // For uls that specifically have a nested ul inside
    $('ul.wrap > li:not(ul ul > li)') // For any top-level ul
    

    For nested li:

    $('ul.wrap ul.wrap > li')
    
    +4
    source

    ul, which is nested in li:

    $("li > ul.wrap > li")
    

    ul, which is not nested in li:

    $("ul.wrap li:not(li > ul >li)")
    
    +1
    source

    - , :

    $("ul.wrap li ul.wrap")
    
    0

    "" ul "" ul. ul , ul.wrap ul.wrap. , : ul.wrap:not(ul.wrap ul.wrap). : ul.wrap, , . "li", , .. > li.

    , , :

    Html:

    <ul class="wrap" tag="outer">
     <li class="out"></li>
     <li class="out"></li>
     <li class="out">
         <ul class="wrap" tag="inner">
            <li class="out"></li>
            <li class="out"></li>
         </ul>
     </li>
    </ul>
    

    JQuery

    alert($('ul.wrap:not(ul.wrap ul.wrap)').attr('tag'));
    alert($('ul.wrap ul.wrap').attr('tag'));
    
    alert($('ul.wrap:not(ul.wrap ul.wrap) > li').length);
    alert($('ul.wrap ul.wrap > li').length);
    

    Ps. "li", .. ul, ( li) -, ?

    0
    source

    Source: https://habr.com/ru/post/1786085/


    All Articles