jquery find li with certain class and add another class

11,662

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();
});
Share:
11,662
Pluda
Author by

Pluda

I’m a Portuguese graphic designer who codes mainly for small projects trying to learn as much as I can. As a self-learning coder I started in 1999 with Macromedia Flash Action Script, some Html and basic Php. For about 5 or 6 years I made some really cool things with Action Script but then the age of iPhone’s arrived and in consequence Flash started to die.. I really liked Flash! I then jumped to jQuery, it was nice, but I was not confortable with Css, Php... I was an Action Scripter! Due health issues I stoped from 2013 until 2018, but now I’m back. At these days I try to not use frameworks, they are awesome, but they limit our own journey into how to make things as they should be.

Updated on June 04, 2022

Comments

  • Pluda
    Pluda almost 2 years

    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

    all items get nivel_1

    what should i do?

    thanks!

    Pluda