I seem to have broken the clone function somehow. My jQuery clone function is relatively simple, but doesn't seem to be working. I have two elements, and I'm trying to copy from one to the other:
<div id="copy"><span>Some stuff to copy.</span></div>
<div id="paste"></div>
jQuery:
$(document).ready(function(){
$('#copy').clone().append('#paste');
});
You can see a codepen here:
I seem to have broken the clone function somehow. My jQuery clone function is relatively simple, but doesn't seem to be working. I have two elements, and I'm trying to copy from one to the other:
<div id="copy"><span>Some stuff to copy.</span></div>
<div id="paste"></div>
jQuery:
$(document).ready(function(){
$('#copy').clone().append('#paste');
});
You can see a codepen here: http://codepen.io/anon/pen/NPrBRq
Share Improve this question asked Dec 19, 2014 at 16:51 alloyalloy 7661 gold badge14 silver badges24 bronze badges 3- 3 Two divs with the same id may have a lot to do with it – danronmoon Commented Dec 19, 2014 at 16:52
- 1 Your goal isn't clear but you might want to use appendTo instead of append. Now you're appending (moving) #paste to a clone you don't put in the page, this can't achieve anything useful. – Denys Séguret Commented Dec 19, 2014 at 16:53
-
3
I was about to say, I think you mean
appendTo
, notappend
– Phil Tune Commented Dec 19, 2014 at 16:54
3 Answers
Reset to default 5Should be:
$(document).ready(function(){
$('#copy span').clone().appendTo('#paste');
});
Fundamentally, append()
and appendTo()
perform the same task, however, appendTo is used for appending to a specific element(which is, I believe, what you were going for). Read more here.
Also, your Pen did not have the jQuery library included.
Two problems with that code:
You want to use
appendTo
, notappend
.a.append(b)
appends the contentb
to the elementa
;a.appendTo(b)
is the other way around, it appendsa
tob
.You need to remove the
id
of the cloned element; if you don't, you create an invalid document, becauseid
s must be unique
So:
$(document).ready(function(){
$('#copy').clone().removeAttr("id").appendTo('#paste');
});
$(document).ready(function(){
$('#copy').clone().removeAttr("id").appendTo('#paste');
});
<div id="copy"><span>Some stuff to copy.</span></div>
<div id="paste"></div>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You should append the cloned element to DOM
$(document).ready(function(){
$('#copy').clone().appendTo('#paste');
});