0

I want to repeat 'post' div and all of its contents eg 50times in left-col div using jquery and call it inside html?

HTML:

 <div class="post"> Content </div>

JS:

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

$(document).ready(function(i) {
for (let i = 2; i < 100; i++) {
  $(".post:eq(0)").clone().appendTo(".left-col");
}


 });

1 Answer 1

1

You can do it like this:

$(document).ready(function(i) {
  for (let i = 0; i < 50; i++) {
    $(".post:eq(0)").clone().appendTo("#left-col");
  }
});

There was a few problems with your code. First $("#post") should be $(".post"), since it's a class not an id.

Second your for loop was not correct. You were missing the {} and also it should be i < 50 not i < i.length(50)

Also important to note that I've added :eq(0) to $(".post"), since it would cause a big problem without. Because first time the loop would run, you would have 1 element with the class post, second time you would have 3 elements, third time = 6 elements and so far.

$(document).ready(function(i) {
  for (let i = 0; i < 50; i++) {
    $(".post:eq(0)").clone().appendTo("#left-col");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post"> Content </div>


<div id="left-col"></div>

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

3 Comments

Thank you, changed it( left-col was also an id) ,how should i call this function in html now? Or it should append it right away to left-col?
Since you have added document ready then you can call it basically where ever you want. since it will not run until the page is ready.
If you have your javascript in its own file, you're good, as long as you make sure it is included. Else include the js code in HTML with a <script> tag.

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.