Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85613

How to append an element multiple times?

I want to append an element multiple times like the following but it is appending more than 33 items:

for(var i=0;i<33;i++){
    $('.selector').clone().appendTo('#another');
}

The problem is occuring as it's cloning and appending all cloned elements. How should I do?

Also, How can I add classes for all .selector like some-1, some-2, ...., some-32?

var el = $('.selector');
for(var i=0;i<33;i++){
    el.clone().appendTo('#another');
    $('.selector').addClass('some-'+i);
}

But it adds to selector some-1,some-2 to each selector but I wanted to do some-1 for first selector some-2 for second selector like so.

Upvotes: 1

Views: 351

Answers (3)

XCS
XCS

Reputation: 28177

Only clone the first one:

var el = $('.selector');
for(var i=0;i<33;i++){
    el.clone().appendTo('#another');
}

Doing this also improves performance as you cache the element (you don't have to search for it in the DOM tree every time you use $('.selector').).

Updated demo, also ads a different class for each new element. http://jsfiddle.net/mvpF9/

el.clone().addClass('some-'+i).appendTo("#another");

Upvotes: 3

billyonecan
billyonecan

Reputation: 20270

As mentioned in another answer here, just cache the original .selector, and clone that.

To add a class to each clone, just use addClass() and use the value of i.

var $selector = $('.selector');

var clones = [];
for (var i=1; i<33; i++) {
    clones.push( $selector.clone().addClass( 'someClass' + i )[0] );
}

$(clones).appendTo('#another');

For performance, the above adds each cloned element to an array, and constructs a jQuery object from it so that the appendTo() method only needs to be called once.

Fiddle

Upvotes: 1

MrHunter
MrHunter

Reputation: 1900

Only select the first element

for(var i=0;i<33;i++){
    $('.selector').first().clone().appendTo('#another');
}

Upvotes: 1

Related Questions