Reputation: 3086
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 & 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>');
}
});
Upvotes: 0
Views: 226
Reputation: 1483
If i understand your question correctly, you should replace
$(this).prepend('<i class="fa fa-caret-right"></i>');
with
$(this).addClass("myAddedClass");
Upvotes: 0
Reputation: 1
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 ">")
Upvotes: 0
Reputation: 66475
$('#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
Upvotes: 1