简体   繁体   中英

Use jquery to check if there are nested ul and lis

I have the following code of nexted uls and lis. I want to add a class with jquery to any li that has a ul child in it. Here is a JSBIN

<ul class="tree" id="tree">

    <li><input type="checkbox" name="account_settings" value="yes">Account Settings
        <ul>
            <li><input type="checkbox" name="one" value="one">AS One</li>
            <li><input type="checkbox" name="two" value="two">AS Two</li>
            <li><input type="checkbox" name="user_roles" value="user_roles">Users &amp; Roles
                <ul>
                    <li><input type="checkbox" name="user_role" value="add">Add</li>
                    <li><input type="checkbox" name="user_role" value="delete">Delete</li>
                </ul>
            </li>
        </ul>
    </li>

    <li><input type="checkbox" name="rl_module" value="yes">RL Module</li>

    <li><input type="checkbox" name="rl_module" value="yes">Accounting
        <ul>
            <li><input type="checkbox" name="vat" value="yes">VAT</li>
            <li><input type="checkbox" name="bank_account" value="yes">Banking
                <ul>
                    <li><input type="checkbox" name="view" value="yes">View</li>
                    <li><input type="checkbox" name="crud" value="yes">CRUD</li>
                </ul>
            </li>
        </ul>
    </li>

</ul>

jQuery

$('#tree > li').each(function(){    
    if($(this).has('ul')){
        $(this).prepend('<i class="fa fa-caret-right"></i>');
    }    
});
$('#tree ul').parent('li').addClass('fa fa-caret-right');

"If I find a ul inside #tree then add a class to it's li parent"

JSBin: http://jsbin.com/kekugopi/2/edit

If i understand your question correctly, you should replace

$(this).prepend('<i class="fa fa-caret-right"></i>');

with

$(this).addClass("myAddedClass");

This should do the trick for just the first level of elemenst:

$('#tree > li').has('ul').prepend('<i class="fa fa-caret-right"></i>');

If you want to use the same code on all li's that have a ul as child use:

$('#tree li').has('ul').prepend('<i class="fa fa-caret-right"></i>');

(notice the missing ">")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM