Tag Archives: Recursion

Add CSS Class Recursively With jQuery

The Function:

function addCSSClassRecursively(topElement, CssClass) {
            function() {
                 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.

%d bloggers like this: