santa
santa

Reputation: 12512

Top level list items only

I need to insert an icon into <li> if that items contains another <ul>.

HTML

<ul>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a>
        <ul>
            <li><a href="#">link</a></li>
            <li><a href="#">link</a></li>
        </ul>
    </li>    
    <li><a href="#">link</a></li>
</ul>

JS

$('ul:first > li').each(function() {
    if ($(this).find('ul').length > 0) {
        $(this).find('a').prepend('<i class="fa fa-caret-down"></i>');
    }
});

Unfortunately currently I get it inserted in every <li> of the second <ul> as well. How do I keep it to the top level only?

$('ul:first > li').each(function() {
    if ($(this).find('ul').length > 0) {
        $(this).find('a').prepend('<i class="fa fa-caret-down">ICON </i>');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><a href="#">link</a></li>
    <li><a href="#">link</a>
        <ul>
            <li><a href="#">link</a></li>
            <li><a href="#">link</a></li>
        </ul>
    </li>    
    <li><a href="#">link</a></li>
</ul>

Upvotes: 2

Views: 310

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240948

Use the :has() selector, $('ul:first > li:has(ul)'), to select the li if it has a child ul element.

In addition, you would need to use the direct child selector within the .find() method so that only direct a child elements are selected $(this).find('>a').

Example Here

$('ul:first > li:has(ul)').each(function() {
    $(this).find('>a').prepend('<i class="fa fa-caret-down"></i>');
});

Upvotes: 3

Related Questions