Hugo Seleiro
Hugo Seleiro

Reputation: 2657

Need to duplicate the same element in the DOM 4 times using Jquery

Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

function Pin(caixaPin){
 var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('<div></div>');

Thanks !!

Upvotes: 1

Views: 95

Answers (4)

treyBake
treyBake

Reputation: 6560

You can use a for loop to create X amount of Y, like this:

for (var j = 0; j <= 3; j++)
{
    $('body').append('<div class="caixaPin"></div>')
}

what this does is define j as 0, when it gets to 3 and including 3, append <div></div> to the body. Hope this helps

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12181

Here you go with jsfiddle https://jsfiddle.net/eL3usbxb/

function Pin(caixaPin){
    for(var i=0; i<4; i++){
        var $temp;
        $temp = $("<div></div>");
        $temp.addClass("caixaPin");
        $temp.html(caixaPin);
        $("body").append($temp);
    }
}

Pin('<div></div>');

Another way Just call Pin function inside a loop

for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}

Upvotes: 2

user5014677
user5014677

Reputation: 694

for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}

There you go. Basic for loop from 0 to 3 (4 times). And calling Pin inside it.

Upvotes: 2

Michał Tkaczyk
Michał Tkaczyk

Reputation: 736

Just execute your function pin in loop

Upvotes: 1

Related Questions