Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a DOM element twice (jQuery)

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.

like image 667
parsa Avatar asked Jul 16 '13 17:07

parsa


People also ask

Can you append multiple items JavaScript?

To append multiple child elements with JavaScript, we can use the append method. Then we write: const listElement = document. querySelector('ul') const listItem = document.

What is the difference between the append () and after () methods in jQuery?

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.

Does jQuery append return?

The returned element from append() is the container and not the new element.


1 Answers

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/

like image 126
krishwader Avatar answered Oct 12 '22 01:10

krishwader