I have a sortable list with nested LI
items. I'm looking for create an ID
for each LI
in the group.
Example. If I have this:
<li class="main"> Cat 0
<ul class="subCat">
<li>Subcat 0
<ul class="subCat">
<li>Sub-Subcat 0
<ul class="subCat"></ul>
</li>
</ul>
</li>
<li>Subcat 1</li>
</ul>
</li>
Ok, those ul.subCat
are there to nest other li
items. I want to make a function to add ID
s to li
elements and its li
child elements. This function will be called by every order change.
The result should be something like this:
<li class="main" id="cat_0"> Cat 0
<ul class="subCat">
<li id="cat_0_0">Subcat 0
<ul class="subCat">
<li id="cat_0_0_0">Sub-Subcat 0
<ul class="subCat"></ul>
</li>
</ul>
</li>
<li id="cat_0_1">Subcat 1</li>
</ul>
</li>
And, for each li.main
element repeat the story to reach 4 levels (0 to 3).
My actual code is this one:
// level 0
target = $('#ulMenu >li');
for( i=0; i<=target.length-1; i++ ){
target.eq(i).attr('id', 'cat_' + i).addClass('main');
}
// level 1
//------------------------------------------------------------------
$('#ulMenu >li.main').each(function(){
target = $(this).children('ul').children('li');
for( i=0; i<=target.length-1; i++ ){
father = target.eq(i).parent('ul').parent('li').attr('id').split('_')[1];
target.eq(i).attr('id', 'cat_' + padre + '_' + i);
}
I have to know how to add ID
s to the rest of elements. I was trying but I can't found with the solution.
Here's a recursive solution that'll work to any depth you want:
function menuID(el, base) {
base = base || 'cat';
$(el).filter('li').each(function(i) {
this.id = base + '_' + i;
menuID($(this).children('ul').children('li'), this.id);
});
};
menuID('.main');
See http://jsfiddle.net/alnitak/XhnYa/
Alternatively, here's a version as a jQuery plugin:
(function($) {
$.fn.menuID = function(base) {
base = base || 'cat';
this.filter('li').each(function(i) {
this.id = base + '_' + i;
$(this).children('ul').children('li').menuID(this.id);
});
};
})(jQuery);
$('.main').menuID();
See http://jsfiddle.net/alnitak/5hkQU/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With