title: jQuery/JavaScript: Cloning with dynamic added content
body: <p>I have a site here where the user can click on some divs. Then I add an "X" to it using this code:</p>
  
  <pre><code>function addEx( elem, insertClass ) {
          var element = $( elem );
          var newInsertClass = insertClass.replace('.', '');
          var insert = "&lt;span class='" + newInsertClass + "'&gt; X &lt;/span&gt;";
  
          element.click(function(){
              var $this = $(this);
  
              if( $this.text().indexOf( "X" ) &gt;= 0 ) {
                  var id = $this.attr( "id" );
                  $( "#" + id + " " + insertClass ).remove();
              } else {
                  $this.append( insert );
              }   
          })
      }
  </code></pre>
  
  <p>As you can see, if the "X" is already there, I remove it. If it's not there, I add it. This works fine.</p>
  
  <p>The user can also click on a "get results" button. The divs the user has clicked are then compared with the right answers. According to this, I add classes to the divs that were clicked correctly, too much or that were forgotten to click. This also works, but the content (the "X") gets lost. So I can see the CSS-stlying I supplied for these classes, but the "X" inside the div is missing after replacing the original with the clone. For adding the classes I use this code:</p>
  
  <pre><code>var test = $(".test");
  var clone = test.clone(true,true);
  
  
  function correction() {
      clone.children().filter(function() {
          return $.inArray('#' + this.id, forgotten) != -1;
      }).addClass("forgotten").end().filter(function() {
           return $.inArray('#' + this.id, toomuch) != -1;
      }).addClass("toomuch").end().filter(function() {
           return $.inArray('#' + this.id, correct) != -1;
      }).addClass("right");
  
     test.replaceWith(clone);                   
   }
  </code></pre>
  
  <p>I clone the element here, then add the appropriate classes on the clone and replace the original with the clone.</p>
  
  <p>So my question is: How can I prevent this loss of content? I guess it's because the "X" are added dynamically? Or I also have more then one element with <code>.test</code> - could this be the cause?</p>