I found a strange thing. When I insert an element into another with the jQuery html() method, the first element is removed from DOM. I want to know if it is possible to insert an element and keep it in DOM.
Here is an example:
$(document).ready(function(){
select1 = $("#select-1");
select2 = $("#select-2");
$("#gap").html(select2); //Original select2 removed from DOM
});
As you can see the #select-2 element is no longer visible if it is inserted into another element. But I want to insert it, and keep the priginal element as before.
Assuming I’ve understood your question correctly, you can
clonethe element:If you need to keep any event handlers that were bound to
select2you can passtrueas an argument toclone.Here’s a working example.
As a side note, notice that I’ve added the
varkeyword before your variable declarations. This prevents the variables from leaking into the global scope (which you usually don’t want).As another side note, it looks like this form of the
htmlmethod is not documented in the jQuery API (it lists.html( htmlString ), and states thathtmlStringshould be a “string of HTML”).The jQuery source however, clearly allows the use of a string, an element or a jQuery object. If
htmlStringis a string, the nativeinnerHTMLproperty is used. If not, theappendmethod is used instead: