Reputation: 2276
In my page I have a div, I wanna move it under another node, I found this:
$("#myDiv").appendTo("#form");
But I got 2 elements of myDiv!
How can I get just one div ?
Upvotes: 0
Views: 120
Reputation: 8515
A quick fix would be:
var myDivHTML = $("#myDiv").html();
$("#myDiv").remove();
$("#form").append(myDivHTML);
Note
That when you remove an element from DOM, you also lose all events bound to this element and all of its children. To fix it you have to bind an event to the parent element which will not be removed, e.x.:
HTML
<div class="will-not-be-removed">
<div class="this-one-will">
<!--stuff here-->
</div>
</div>
JS
$(".will-not-be-removed").on("click", ".this-one-will", function(e){
console.log("Click!");
});
Now your event will not be lost until inner DIV stays inside outer DIV after removing/moving. Otherwise, you have to bind an event to another element which is higher in DOM.
Upvotes: 1