Jquery-Clone() append

clone, jquery

Solution

Is this what you are trying to do?

function Repeat(obj)
{
 var currentDiv = $(obj).parent("div");
 currentDiv.clone().insertAfter(currentDiv);
}

UPDATE: If you want nesting, try this:

<div id="maindiv">
  <ul>First
   <li>
    <label>Sub-first</label> 
    <input type="button" class="repeat1" onclick="Repeat(this)"/>
   </li>
 </ul>

 <ul>Second
  <li>
   <label>Sub-second</label> 
   <input type="button" class="repeat1" onclick="Repeat(this)"/>
  </li>
 </ul>

 <ul>Third
  <li>
   <label>Sub-third</label> 
   <input type="button" class="repeat2" onclick="Repeat(this)"/>
  </li>
 </ul>   
</div>

<script>   
function Repeat(obj)
  {
    var CurrentLi = $(obj).parent("li");
    CurrentLi.clone().insertAfter(CurrentLi);
  }
</script>

Problem

I am facing an issue whlie trying to clone a parent div and then appending it directly under itself. My function works fine as long as the last node is selected so: ``` <div> <div> A </div> <div> B </div> <div> C </div> </div> ``` will result in ``` <div> <div> A </div> <div> A.1 </div> <div> B </div> <div> C </div> </div> ``` If i clone A. But if I clone A again I get. ``` <div> <div> A </div> <div> A.1 </div> <div> A </div> <div> A.1 </div> <div> B </div> <div> C </div> </div> ``` while I would like ``` <div> <div> A </div> <div> A.1 </div> <div> A.1 </div> <div> B </div> <div> C </div> </div> ``` My markup and code are below: ``` <div id="maindiv"> <div> <label>First</label> <input type="button" class="repeat1" onclick="Repeat(this)"/> </div> <div> <label>Second</label> <input type="button" class="repeat1" onclick="Repeat(this)"/> </div> <div> <label>Third</label> <input type="button" class="repeat2" onclick="Repeat(this)"/> </div> </div> function Repeat(obj) { var CurrentDiv = $(obj).parents("div[class^='repeat']:first"); $(CurrentDiv).clone().appendTo(CurrentDiv).end(); } ``` I also have a similar issue with deleting where all the child nodes are deleted while I just want a single div removed. Any help would be appreciated. The remove function is ``` function Remove(obj) { var CurrentDiv = $(obj).parents("div[class^='repeat']:first"); CurrentDiv.remove(); } ```

Original source