Add CSS Class Recursively With jQuery

The Function:

function addCSSClassRecursively(topElement, CssClass) {
    $(topElement).addClass(CssClass);
    $(topElement).children().each(
            function() {
                 $(this).addClass(CssClass);
                 addCSSClassRecursively($(this), CssClass);
            });
}

Pretty simple. The first line adds the class to the element passed in. Next, using the jQuery.children() and jQuery.each() functions it iterates through each child element adding the CSS Class and then calls itself to add the CSS class to each of the child’s children elements.

Calling it:

$(function() {
   addCSSClassRecursively($('#div1'), 'MasterCssClass');
});

In my implementation I call the function when the DOM is fully loaded, using the jQuery.ready() function. I just pass in the parent or top level element I want to start adding the class at and the functions does the rest.

Advertisements

About Shawn Sweeney

I'm a father, software developer, and runner. I blog about things related. View all posts by Shawn Sweeney

3 responses to “Add CSS Class Recursively With jQuery

  • Robert Price

    It looks like you can shorten this, and delete the line
    $(this).addClass(CssClass);

    The class will get added anyway when addCSSClassRecursively is called in the next line.

    • Shawn Sweeney

      You’re correct. I noticed the same thing when I was reviewing my unit tests. This is a good example of how TDD can make a difference. Instead I opted to write unit tests after the fact, and missed that.

      On a side note, It does appear that the jQuery.addClass method does not add the class when it already exists.

      Thanks Robert

  • Derek Anderson

    You can do this with 1 line

    $(“*”, “#parent”).addClass(“test”).parent().addClass(“test”);​​​​​​​

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: