Can someone explain why the following snippet does not add <foo>
to both #a
and #b
?
HTML:
<div id="a"></div>
<div id="b"></div>
JS:
$(function(){
var $foo = $("<foo>HI</foo>");
$("#a").append($foo);
$("#b").append($foo);
});
jsfiddle
Edit: thanks for the helpful points, the fact that .append()
moves the element explains this behavior. Since the element in my application is actually a Backbone View's .el
, I prefer not to clone it.
To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.
The . append insert the parameter element inside the selector element's tag at the last index position, whereas the . after puts the parameter element after the matched element's tag.
The returned element from append() is the container and not the new element.
Try clone
. This, as the name implies, will copy the $foo
element and not move, like append
will do.
$(function(){
var $foo = $("<foo>HI</foo>");
$("#a").append($foo.clone());
$("#b").append($foo.clone());
});
But, why not just use this?
$("#a,#b").append($foo);
This will also work :)
Here's a demo for both these situations : http://jsfiddle.net/hungerpain/sCvs7/3/
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