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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With