Thursday, October 6, 2016

Append additional html to cloned object in jquery

Leave a Comment

I want to add additional html in the cloned object.

var item = $("#clone")     .clone(true, true)     .attr({"id": "citem", "class": "row cartItem_" + item_id})     .css('display', 'block')     .appendTo("#all-items"); 

I know about wrap method but that is something else. I want to append html after this cloned object. Or somehow i can manipulate the HTML of the cloned object element.

6 Answers

Answers 1

This approach is to explain how the .clone() works, and covers all the states you ever mentioned in the question, such as..

  1. Creating a clone of a DOM
  2. Appending additional raw HTML to a clone
  3. Manipulating the clone
  4. Manipulating the content in the clone
  5. Clone in another clone
  6. Appending another clone to a clone

$(function() {    // 1. cloning the HTML    var $clonedContent = $('.content').clone();      // 2. Manipulate the cloned element    // -- Update the existing content    $clonedContent.find('h5').text("My content just got manipulated");      // -- Adding raw HTML content    $clonedContent.append("<small> It's a raw HTML </small>");      // -- Adding property to an existing content    $clonedContent.find('small').addClass('make-me-day');      // Getting another cloned content    var $anotherClonedContent = $('.content').clone();        // Another manipulation of another cloned content    $anotherClonedContent.find('h5').text("This is another cloned content");        // Manipulate the another cloned content's content    $anotherClonedContent.find('h5').addClass('make-me-day');      // Add another cloned content to the already manipulated and cloned content.    $clonedContent.append($anotherClonedContent);      // Add the final clonedContent to other DOM    $('#main').append($clonedContent);  });
.make-me-day {    color: red;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="main">    <div class="content">      <h5> Just a simple content </h5>    </div>  </div>

Answers 2

I think that's more easy than you imagine:

$(function(){    var item_id=0;        // function to clone your element    var newItem=function(){      item_id++;      return $('#clone')        .clone(true, true)        .attr({'id':'citem_'+item_id, 'class':'row cartItem_'+item_id})        .css('display','block')        .appendTo('#all-items');    };        // Clone element and edit what you want    newItem().html('hobby').css('color','blue');      // Clone element and append what you want    newItem().append(' - <i>spaghetti</i>');        // You can also find element by id    $('#citem_2').css('color','red');        //You can add buttons to do it    $('button:eq(0)').on('click',function(){      newItem().html('Your <b>html</b> here.');    });    $('button:eq(1)').on('click',function(){      newItem().append(' - Your <b>html</b> here.');    });  });
<button>New clone</button>  <button>New clone + append</button>  <div id="all-items">    <div id="clone">pizza</div>  </div>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Answers 3

I took a close look to all answers and comments to this bounty question...

I can see that the bidder is kind of demanding, which is okay since 100 rep. points is valuable.

I think that the question contains two, in fact.

  1. How to clone
  2. How to «manipulate the HTML of the cloned object» - Wasif Iqbal on Sep 22th.

I think the question is intended to get explanations on how to manipulate the clone, not only on creation and appending to somewhere, but also afterward.

I really think my very cool example below could be a «valid answer» - Vixed on Sep 29th.
The other answers were good too, anyway... So a made a supplemental effort.
;)

First explanation of all:
Cloning an element is done by jQuery .clone(). So have a nice reading.

Then:
jQuery chaining is nice to append some other stuff «inside» or «before/after» the clone in a concise way, as demonstrated in other answers.

But to manipulate it afterward, like in another click event handler...
This is the trick to know, which is not explained in the previous reference:

  • You have to make sure to set a unique id attribute to it, instead of the same id as the original.

Because you know that an id shall be unique!

«One ring to rule them all.
One ring to find them, one ring to bring them all and in the darkness bind them.»


- A well known deamon said this while forging a curse...


Then... What more explanation could I give if it ain't clear?
Alert reader should have understood everything already.

I made a funny «clone-and-kill-it-game» to demontrate cloning and further manipulations.
For the «inspiration», I have to admit that I saw a japaneese zombie movie yesterday night...
lol!

Have fun with this code snippet:
(also on CodePen)

// Constants  var number = 1;  var revealed = false;    // The cloning function  $("#cloneIt").click(function(){      var cloning = $("#Human")      .clone()      .attr({"id": "Clone_number_"+number, "class":"clone"})      .appendTo("#CloneBucket");        $(this).val("Clone him again! It's fun!");        number++;      if(number==4){          $(".reveal").show();      }      if(number==9){          $(this).val("Enought! This is now illegal.").prop("disabled",true);      }        // Add them to select      var options="<option disabled selected class='deceased'>KILL THEM!</option>";      for (i=1;i<number;i++){          if( $("#CloneBucket").children().eq(i-1).hasClass("dead") ){              options += "<option value='"+i+"' class='deceased'>Clone #"+i+"</option>";          }else{              options += "<option value='"+i+"'>Clone #"+i+"</option>";          }      }      $("#cloneSelect").html(options);        if(revealed){          reveal();   // Sub function to add clones to a select element.      }  });    // Reveal clone numbers  $(".reveal").click(function(){      reveal();        setTimeout(function(){          $(".reveal").val("Kill a clone! (While it's not illegal!)").removeClass("reveal").addClass("shoot");      },50);    });    // Kill button  $("#page").on("click",".shoot",function(){      $(this).prop("disabled",true).val("Select one");      $("#cloneSelect").show();  });    // Select kill target  $("#cloneSelect").change(function(){      var thisCloneIs = parseInt($(this).val());      var niceShot = "#Clone_number_"+thisCloneIs;      $(niceShot).css({"opacity":0.3,"color":"red"});      $(niceShot+" .definition").html("I was the number"+thisCloneIs).parent().addClass("dead");        // Redish the option      $(this).find("option").eq(thisCloneIs).prop("disabled",true).addClass("deceased");      $(this).find("option").eq(0).prop("selected",true);        // Bravo!      var allDead = [];      setTimeout(function(){          $("#cloneSelect").find("option").each(function(index){                if( $("#cloneSelect").find("option").eq(index).hasClass("deceased") ){                  allDead.push(true);              }else{                  allDead.push(false);              }          });            if( allDead.indexOf(false)==-1 ){                // Reset this super gaming experience for a new.              $("#CloneBucket").html("");              $(".shoot").addClass("reveal").removeClass("shoot").val("Reveal clone numbers!").prop("disabled",false).hide();              $("#cloneIt").val("Clone again?").prop("disabled",false);              $("#cloneSelect").html("").hide();              revealed = false;              number = 1;          }      },50);  });    function reveal(){      $(".clone .definition").each(function(index){          var cloneIndex = index+1;   // zero-based          $(this).html("I'm the number "+cloneIndex);          revealed = true;      });  }
img{      width:60px;  }  div{      text-align:center;  }  .reveal{      display:none;  }  #CloneBucket div{      display:inline-block;      padding:10px;  }  #CloneBucket{      margin:0 auto;      text-align:center;  }  select{      display:none;      margin:0 auto;  }  .deceased{      color:red;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>  <div id="page">      <input type="button" id="cloneIt" value="Want to clone him?"><br>      <br>      <div id="Human">          <img src="http://image.flaticon.com/icons/svg/10/10522.svg"><br>          <span class="definition">I'm a real human!</span>      </div>      <br>      <input type="button" class="reveal" value="Reveal clone numbers!">      <select id="cloneSelect"></select>        <div id="CloneBucket"></div>      <br>  </div>

Answers 4

Assuming you are trying to add html after the clone:

$("#toclone")     .clone()     .attr({"id":"cloned"})     .appendTo("#all-items")     .after("<div>some more content <em>after</em> the clone</div>"); 

The .appendTo() returns the element that was appended, so you can then manipulate it as required, eg using .after()

Answers 5

Still waiting for clarification in the comments, but I think this solution is what you are looking for:

$('button').click(function() {    $('#clone').clone()      .append('<span style="color:red;">some other elements</span>')      .removeAttr('id')      .appendTo('#all-items');  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    <button>Click to clone</button>  <div id="all-items">    <div id="clone">pizza</div>  </div>

Since the appendTo returns the original element that was appended, you can use after on the returned value to add some new element after the cloned element that you just appended:

$('button').click(function() {    $('#clone').clone()      .append('<span style="color:red;">some other elements</span>')      .removeAttr('id')      .addClass('cloned')      .appendTo('#all-items')      .after('<div>this element was added after the cloned element (no blue border here)</div>');  });
.cloned {    border: 1px solid blue;    margin: 5px;    padding: 5px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    <button>Click to clone</button>  <div id="all-items">    <div id="clone">pizza</div>  </div>

Answers 6

One can add to a collection at any time using jQuery's add() function.
This effectively adds to the collection, placing whatever is passed to add() after the clone itself, answering the question

"I want to append html after this cloned object"

var more1 = $('<span />', {html : '<em> and will</em>'}); // element(s) to add  var more2 = '<span> happen again....</span>'; // or strings of HTML for that matter          var item  = $("#clone").clone(true, true)                         .attr({"id": "citem"})                         .show()                         .add(more1) // add whatever after the clone                         .add(more2) // before appending everything                         .appendTo("#all-items");            
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <span id="clone">      <span>All of this has happened before</span>  </span>  <br /><br /><br />  <div id="all-items"><!-- clone goes here --></div>

From the documentation

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.
The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

example : $("p").clone().add("<span>Again</span>").appendTo(document.body);

Manipulating the content inside a clone is done in the exact same way as manipulating any other collection with jQuery

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment