jquery find li with certain class and add another class
I'm not getting how to loop a ul and just add a class if li has class='parent'
I always get each li with my new class...
this is the code
$('.navigation').find('li').each(function() {
if($(this).hasClass('parent')) {
$(this).find('li').each(function() {
$(this).addClass("nivel_1");
$(this).css('display', 'none');
if($(".nivel_1").hasClass('parent')) {
$(".nivel_1").find('li').each(function() {
$(this).addClass("nivel_2");
$(this).css('display', 'none');
});
开发者_开发技巧 }
});
}
});
this is what i get
what should i do?
thanks!
Pluda
So you have a tree view and those with a list within have a class called parent.
I haven't tested this (and I don't know if jQuery has something built in to do this) but you could try something like:
$(document).ready(function(){
$('.navigation').find('li.parent > ul > li').addClass('nivel_X');
$('.nivel_X').each(function(){
var level = $(this).parents('.parent').size();
$(this).removeClass('nivel_X').addClass('nivel_'+level);
});
});
The idea is that you'll add a class to each immediant child of a li with the "parent" class and then name that class nivel_X where X is replaced by the number of parents it finds above...
The following code works too and I like it better:
$('.navigation').find('li.parent > ul > li').addClass(function() {
return 'nivel_'+$(this).parents('.parent').size();
});
you don't really need to do a loop. To be honest though, your code seems much more complicated than the description of your problem, so perhaps this is too simple.
$('li.parent').addClass("nivel_1");
精彩评论