BRBT
BRBT

Reputation: 1487

Cloning and appending a div

I am trying to clone a div and all of its children, and append the clone onto the end of the original when the user clicks a button and change the id of child element, but for some reason I can't even get my div to clone and append.

<div id="section">
    //bunch of textboxes, labels, etc.
</div>

Here is my button

<input type="button" value="Add New Section" id="addSection"/>

Here is my Jquery

$(function() {
    var $section = $("#section").clone();  

    $( "#addSection" ).click(function() { 
        $section.append(); // I've tried this and appendTo, Insert, InstertAfter, After, etc.. still cannot get this to work.. 
    });
});

Ignore the fact that this doesn't change any child element id's, why is this not cloning and appending?

EDIT

I guess to clarify, I am trying to clone the original state of my div and append that every time my button is clicked.

Upvotes: 0

Views: 6186

Answers (4)

Shaunak D
Shaunak D

Reputation: 20626

You need to specify a selector to append the element to.

$('#section').append($section)

Or

$section.appendTo('#section')

Or use .after() to insert the cloned element after the original.

$('#section').after($section)

Edit : You need to clone the element after click to make it work everytime.

So integrated function,

$(function(){
    $( "#addSection" ).click(function(){
        var $section = $("#section").clone();  
        $section.attr('id','someUniqueId');
        $('#section').after($section); 
    });
});

Demo

Upvotes: 1

Nielarshi
Nielarshi

Reputation: 1136

You need to pass the content in jQuery's append function.

Ex -

$('#YOUR_ELEMENT_ID').append('YOUR_CONTENT')

Here it will be like,

$(function() {    
  var $section = $("#section").clone(); 
    $( "#addSection" ).click(function() { 
        var $sectionClone = $section.clone();
        $('#section').append($sectionClone); 
    });
});

Working Demo HERE

Upvotes: 2

Daniel Eisenhardt
Daniel Eisenhardt

Reputation: 593

Try this:

$(function(){
  var $section = $("#section").clone();  

  $( "#addSection" ).click(function() { 
    $("#section").append($section);
  });
});

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

Assuming you want to insert the cloned section after the original, we'd want to clone on the click (not before), so this will work if called more than once.

Then we replace the id (I'm using the current time to make the id unique, you could do something else), and insertAfter() to place it after our original element:

$("#addSection").click(function() {

  var section = $("#section").clone();

  section.attr('id', 'section' + (new Date()).getTime());

  section.insertAfter( $('#section') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="section">
  <p>bunch of textboxes, labels, etc.</p>
</div>

<input type="button" value="Add New Section" id="addSection" />

Upvotes: 1

Related Questions