Wrap any amount of elements with jQuery

Update : Get the nwrapper plugin from the official jQuery plugins site.

jQuery provides a large variety of functions for element manipulation, that in most cases will manipulate the selected elements in no time. A very useful function for every day manipulation is the .wrap() function that we can use to wrap an HTML structure around each jQuery element. But what happens when we want to wrap an HTML structure on every n’th number of the selected elements? Unfortunately, jQuery doesn’t provide any options to the warp function in order to to do something similar.

After a bit of search I came across this solution for the jQuery forum, and created the below jQuery plug in.

(function($) {  
  
$.fn.nwrapper = function(options){  
  
    var defaults = {  
        wrapEvery      : 1,  
        defaultClasses : true,  
        extraClasses   : false,  
        htmlStructure  : 'div'  
    };  
  
    settings = $.extend({}, defaults, options);  
  
    var elements    = $(this).children();  
    var elementsLen = elements.length;  
  
    for ( var i = 0, numb = 1; i < elementsLen; i += settings.wrapEvery, numb++ ){  
  
        // Default Classes Array  
        var classes = [];  
        if ( settings.defaultClasses ) {  
  
            classes[0] = 'wrapper';  
            classes[1] = 'wrapper-' + numb;  
  
            if (numb==1) {  
                classes[2] = 'first';  
            }  
  
            if (numb==Math.ceil(elementsLen/settings.wrapEvery)) {  
                classes[2] = 'last';  
            }  
  
        }  
  
        // Merge Default class with Extra Class  
        if ( settings.extraClasses ) {  
            $.merge( classes, settings.extraClasses );  
        }  
  
        // If you find any classes crete the class string  
        if ( classes.length > 0 ) {  
            htmlClassesString = 'class="' + classes.join(" ") + '"';  
        } else {  
            htmlClassesString = '';  
        }  
  
        elements.filter(':eq(' + i + '), :lt(' + (i + settings.wrapEvery) + '):gt(' + i + ')').wrapAll('<' + settings.htmlStructure + ' ' + htmlClassesString + ' />');  
  
    }  
  
    return $(this);  
};  
  
})(jQuery);

$('#container').nwrapper({  
    wrapEvery      : 2,  
    //defaultClasses : true,  
    //extraClasses   : ['class1', 'class2'],  
    //htmlStructure  : 'span'  
});Check out this Pen!

To use it, select the parent element of the elements you want to wrap, choose how often you’ll apply the wrap (wrapEvery attribute – default is 1), choose if you need any default classes or even provide your own extra classes (extraClasses), and finally provide the HTML structured element you’ll use for a wrapper (the default is div, but you can also use a span).

Now you can wrap every n’th of your elements.

19 thoughts on “Wrap any amount of elements with jQuery”

  1. Thanks very much Yiannis, this looks great.
    Unfortunately I have no brains and can’t get it to work.
    Could you give an example of some html to run to help me understand or at least to check where I have gone wrong (a jsfiddle would be even better!)?
    Sorry and thanks again

  2. Thanks very much for doing that.
    I am still too stupid to make it work.
    What would the function and styles look like if say, you wanted to make every third number red?
    Or maybe I should just wait and read the documentation πŸ™‚
    Thanks

  3. Hello again Neil,

    Well what you’re saying is a style issue, and it has nothing to do with Javascript. Have a look at this atricle on how to achieve what you want. My plug in just wraps elements (with many parameters)…

  4. Sorry, I am wasting your time with my questions. I shall just read the documentation when you publish it and grok it from there. πŸ™‚

  5. Hello,

    I am newbie I have searched anywhere and the jQuery forum suggested me to go here. I’ve tried the plug in, it was a bit mess at first but the demo page really helped.

    thanks
    Lenore

  6. Hi!

    I very much like the plugin … have 1 question thou… how can I unwrap or undo the wrapping of the elements?

  7. Hi, thanks for this such a great plugin. It really helped me a lot.

    One question.. Is possible for this plugin to get work/combining with some plugins out there, such as slidejs or jquery cycle?

    Thanks!

  8. Unfortunately I cannot embed it to other plug ins, although it works just fine with other plug ins (you won’t face any problems).

    I’ve use it many times with the cycle plug in and it works fine…

  9. Pingback: Beauty

Leave a Reply