Kristian
Kristian

Reputation: 1388

Appending object instead of reference

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!

Upvotes: 0

Views: 28

Answers (1)

JNF
JNF

Reputation: 3730

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>

Upvotes: 2

Related Questions