0

I'm using the following:

 var topWrapper = $('<div />')
    .addClass( 'table-top-wrapper ui-corner-top ui-body-'+o.wrapperTheme )
    .grid({ grid: this.options.grid })
    .append(container)
    .insertBefore(table);

and need to append x children to this div before calling .grid.

Say x=3 is there a way to append x number of child divs to the newly created div element in the chain? Somethingl Like a chainable for-loop?

Thanks for insights!

frequent
  • 27,643
  • 59
  • 181
  • 333
  • 1
    checkout this article for inserting multiple identical elements: http://stackoverflow.com/questions/201530/how-should-i-add-multiple-identical-elements-to-a-div-with-jquery – Ben Sewards Sep 28 '12 at 19:22
  • Sure, why not just roll your own! Something like this [FIDDLE](http://jsfiddle.net/raUsP/) ?? – adeneo Sep 28 '12 at 19:30
  • Why must it be done in a single chain? – Kevin B Sep 28 '12 at 19:33

3 Answers3

4

You can create an array of elements and append:

var x = 3;

var topWrapper = $('<div />')
.addClass( 'table-top-wrapper ui-corner-top ui-body-'+o.wrapperTheme )
.append($.map(new Array(x), function(){
  return $('<div/>');
}))
.grid({ grid: this.options.grid })
.append(container)
.insertBefore(table);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I like this best. Very nice and something I have to remember the next time, I'm sitting on this! Thanks again! – frequent Sep 28 '12 at 19:40
2

You could create your own jQuery extension like this:

$.fn.appendMultipleChildren = function(child, repeat) {
    var $this = $(this);
    for (var i = 0; i < repeat; i++) {
        $this.append(child.clone());
    }
    return $this;
}

then call

 var topWrapper = $('<div />')
    .addClass( 'table-top-wrapper ui-corner-top ui-body-'+o.wrapperTheme )
    .grid({ grid: this.options.grid })
    .appendMultipleChildren($('<div />'), 3)
    .append(container)
    .insertBefore(table);

Edit - and here's a jsfiddle example: http://jsfiddle.net/eJGxm/

Laurence
  • 1,673
  • 11
  • 16
1

The most efficient way to do it is to assemble them into a single string and then call jQuery.html. This doesnt make the loop chainable though. If you really want to do it you can wrap them in a function:

topWrapper = $('<div />')
    .addClass( 'table-top-wrapper ui-corner-top ui-body-'+o.wrapperTheme )
    .html((function(){
       var markup = '';
       for (var i =0; i < 3; i++) {
         markup .= '<div></div>';
       }
       return markup;
    })())
    .grid({ grid: this.options.grid })
    .append(container)
    .insertBefore(table);

Personally though i find that harder to read than doing the loop before you make your topWrapper calls.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114