Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery clone element and insertAfter

Tags:

jquery

I am trying to clone a simple div and insert it after itself:

$(document).ready(function() {

  // clone and append
  $("div").clone().appendTo("div");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 10px; background-color: blue; width: 600px; margin-bottom:1px"></div>

Why is this not working as I expect it to?

like image 459
Robert Rocha Avatar asked Sep 13 '25 12:09

Robert Rocha


2 Answers

If you want to insert the element after the exsisting one, then you shoud use .inserftAfter()

$(() => {
  $('div').clone().insertAfter('div');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 25px; background-color: blue; width: 25px; margin-bottom:1px"></div>
like image 119
halfzebra Avatar answered Sep 16 '25 09:09

halfzebra


Append to a parent container instead

$(document).ready(function() {

  // clone and append
  $("div").clone().text('cloned div').appendTo("body");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div style="background-color: blue; width: 600px; margin: bottom:1px">original div</div>

appendTo('div') did not work because it inserted the cloned div at the end but within the existing div.

like image 36
AmmarCSE Avatar answered Sep 16 '25 08:09

AmmarCSE