0

How can I instantiate an existing div element using javascript? Lets say I have:

    <div class="container">
    <div class="myclass">TROLL FACE</div>
    </div>

I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?

Please help, thanks.

4 Answers 4

2

You may want the .clone method.

var ele = $('.myclass');

for (var i = 0; i < 5; i++) {
    ele.clone().appendTo('.container');
}

The live demo.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, have you tried this code? I dont know but its not working on me.
@user1577161 Added the demo, check it.
1
var container = $('.container');
for (var i = 0; i < 5; i++) {
    container.append('<div class="myclass">TROLL FACE</div>');
}

You could use the .append() method.

3 Comments

Yes, of course that I have tried it. It works perfectly fine. Here's a live demo: jsfiddle.net/KQ7jb
Thanks, for some reason its not working when I just put it on a script tag over the head. I have to put it on an external js because I am using one.
This code seems to require the jQuery Framework. I recommend you to use a JS-Framework, because it handle many Crossbrowser problems for you. If you want a solution without jQuery edit your question
1

With or without JQuery:

for (var i = 0; i < howMany; ++i) {
    // pure js
    var div = document.createElement('div')
    div.classList.add('myclass')
    somePlace.appendChild(div)

    // jquery
    $("<div></div>").addClass('myclass').appendTo(somePlace)
}

Comments

1

Try this

<div class="container">
    <div class="myclass">TROLL FACE</div>
</div>

var $container = $('.container');
var $myclass = $('.container').html();

var mycount ; // Your count

for(var i =0;i< mycount ; i++){
   $container.append($myclass)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.