Search code examples
javascriptjqueryfor-loopchainingcreateelement

Is there a way to add x elements as children of a newly created element in a Jquery chained statement?


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!


Solution

  • 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);