0

I'm trying to add multiple div's within a div inside for loop:

  for( i=0; i<10; i++ )
  {
      $('#parent').append('<div class="child"></div>");
  }

This works perfectly, but when I do:

  for( i=0; i<10; i++ )
  {
      var child = $('<div/>', { class: 'child' });
      $("#parent").append(child);
  }

I get very strange results, I believe it's because using the second method, the reference instead of the object itself is passed. How can I pass just pure object, no reference, to the append method? thanks!

2
  • what do you mean by strange Commented Mar 26, 2015 at 8:57
  • 2
    your code looks just fine for me - jsfiddle.net/arunpjohny/po6uxpLf/1 - if the child object is created within the loop Commented Mar 26, 2015 at 9:03

1 Answer 1

2

Use jQuery cloning

$("#parent").append(child.clone());

You are appending the same object over and over, so nothing happens. It's just taking the element and putting it back in the same place.

The clone makes sure it's a fresh object which is a copy of the original.

Out of above link:

Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

... given the code:

$( ".hello" ).appendTo( ".goodbye" );

The resulting DOM structure would be:

<div class="container">
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

To prevent this and instead create a copy of the element, you could write the following:

$( ".hello" ).clone().appendTo( ".goodbye" );

This would produce:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>
Sign up to request clarification or add additional context in comments.

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.