Search code examples
javascriptjqueryhtmldynamicclone

jQuery Cloning Altered Content


I am trying to run jQuery .clone() on content that has just been altered with .html(). However, .clone is copying content from before it was altered. I want to clone the altered content. How do I do this?

Here is my HTML:

<div id="cloneThis">This text exists before .html() replaces it.</div>
<div id="cloneHere"></div>

Here is my JS:

// This function copies #cloneThis content over to #cloneHere
function cloneStuff(){
  $('#cloneThis').clone().appendTo('#cloneHere');
}

function changeThenClone(){
  $("#cloneThis").html("This is new text that should be cloned.", cloneStuff());
}
// When this is run, cloneStuff() clones the old content, not the new content. 
changeThenClone();

Here's an identical codepen demonstration if you want to see it in action: http://codepen.io/anon/pen/JoRWMQ

Why isn't .clone() copying the altered content? How do I make it clone the altered content instead of the old content?


Solution

  • You're calling cloneStuff() before the actual HTML replacement is being done by the html() function.

    Try this instead:

    $("#cloneThis").html("This is new text that should be cloned.");
    cloneStuff();
    

    Also, jQuery html() method only accepts 1 argument (the new HTML content), see documentation.