admin管理员组文章数量:1126103
I would like to move one DIV element inside another. For example, I want to move this (including all children):
<div id="source">
...
</div>
into this:
<div id="destination">
...
</div>
so that I have this:
<div id="destination">
<div id="source">
...
</div>
</div>
I would like to move one DIV element inside another. For example, I want to move this (including all children):
<div id="source">
...
</div>
into this:
<div id="destination">
...
</div>
so that I have this:
<div id="destination">
<div id="source">
...
</div>
</div>
Share
Improve this question
edited Nov 12, 2022 at 5:03
Peter Mortensen
31.6k22 gold badges109 silver badges133 bronze badges
asked Aug 14, 2009 at 20:14
Mark RichmanMark Richman
29.7k26 gold badges104 silver badges163 bronze badges
4
- 27 Just use $(target_element).append(to_be_inserted_element); – Mohammad Areeb Siddiqui Commented Jun 27, 2013 at 20:07
- 5 Or: destination.appendChild(source) using plain javascript – luke Commented Nov 15, 2016 at 22:10
- can we achieve this using CSS ? is that possible ? – Raj Kumar Samala Commented Mar 8, 2017 at 15:00
- 11 @RajKumarSamala CSS can't alter the structure of the HTML, only its presentation. – Mark Richman Commented Mar 8, 2017 at 18:49
16 Answers
Reset to default 1950You may want to use the appendTo
function (which adds to the end of the element):
$("#source").appendTo("#destination");
Alternatively you could use the prependTo
function (which adds to the beginning of the element):
$("#source").prependTo("#destination");
Example:
$("#appendTo").click(function() {
$("#moveMeIntoMain").appendTo($("#main"));
});
$("#prependTo").click(function() {
$("#moveMeIntoMain").prependTo($("#main"));
});
#main {
border: 2px solid blue;
min-height: 100px;
}
.moveMeIntoMain {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">main</div>
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>
<button id="appendTo">appendTo main</button>
<button id="prependTo">prependTo main</button>
My solution:
Move:
jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
copy:
jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.
Use a vanilla JavaScript solution:
// Declare a fragment:
var fragment = document.createDocumentFragment();
// Append desired element to the fragment:
fragment.appendChild(document.getElementById('source'));
// Append fragment to desired element:
document.getElementById('destination').appendChild(fragment);
Check it out.
Try plain JavaScript? destination.appendChild(source);
.
addEventListener(
"click",
() =>
document.getElementById("destination")
.appendChild(
document.getElementById("source")
)
);
div {
margin: .1em;
}
#destination {
border: solid 1px red;
}
#source {
border: solid 1px gray;
}
<div id="destination">
###
</div>
<div id="source">
***
</div>
I just used:
$('#source').prependTo('#destination');
Which I grabbed from here.
If the div
where you want to put your element has content inside, and you want the element to show after the main content:
$("#destination").append($("#source"));
If the div
where you want to put your element has content inside, and you want to show the element before the main content:
$("#destination").prepend($("#source"));
If the div
where you want to put your element is empty, or you want to replace it entirely:
$("#element").html('<div id="source">...</div>');
If you want to duplicate an element before any of the above:
$("#destination").append($("#source").clone());
// etc.
You can use:
To insert after,
jQuery("#source").insertAfter("#destination");
To insert inside another element,
jQuery("#source").appendTo("#destination");
You can use the following code to move the source to the destination:
jQuery("#source")
.detach()
.appendTo('#destination');
Try the working CodePen.
function move() {
jQuery("#source")
.detach()
.appendTo('#destination');
}
#source{
background-color: red;
color: #ffffff;
display: inline-block;
padding: 35px;
}
#destination{
background-color:blue;
color: #ffffff;
display: inline-block;
padding: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="source">
I am source
</div>
<div id="destination">
I am destination
</div>
<button onclick="move();">Move</button>
If you want a quick demo and more details about how you move elements, try this link:
http://html-tuts.com/move-div-in-another-div-with-jquery
Here is a short example:
To move ABOVE an element:
$('.whatToMove').insertBefore('.whereToMove');
To move AFTER an element:
$('.whatToMove').insertAfter('.whereToMove');
To move inside an element, ABOVE ALL elements inside that container:
$('.whatToMove').prependTo('.whereToMove');
To move inside an element, AFTER ALL elements inside that container:
$('.whatToMove').appendTo('.whereToMove');
I need to move content from one container to another including all the event listeners. jQuery doesn't have a way to do it, but the standard DOM function appendChild does.
// Assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);
Using appendChild removes the .source* and places it into target including its event listeners: Node.appendChild() (MDN)
You may also try:
$("#destination").html($("#source"))
But this will completely overwrite anything you have in #destination
.
You can use pure JavaScript, using appendChild()
method...
The appendChild() method appends a node as the last child of a node.
Tip: If you want to create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.
You can also use this method to move an element from one element to another.
Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.
So you can do that to do the job, this is what I created for you, using appendChild()
, run and see how it works for your case:
function appendIt() {
var source = document.getElementById("source");
document.getElementById("destination").appendChild(source);
}
#source {
color: white;
background: green;
padding: 4px 8px;
}
#destination {
color: white;
background: red;
padding: 4px 8px;
}
button {
margin-top: 20px;
}
<div id="source">
<p>Source</p>
</div>
<div id="destination">
<p>Destination</p>
</div>
<button onclick="appendIt()">Move Element</button>
I noticed huge memory leak & performance difference between insertAfter
& after
or insertBefore
& before
.. If you have tons of DOM elements, or you need to use after()
or before()
inside a MouseMove event, the browser memory will probably increase and next operations will run really slow.
The solution I've just experienced is to use inserBefore instead before()
and insertAfter instead after()
.
Dirty size improvement of Bekim Bacaj's answer:
div { border: 1px solid ; margin: 5px }
<div id="source" onclick="destination.appendChild(this)">click me</div>
<div id="destination" >...</div>
For the sake of completeness, there is another approach wrap()
or wrapAll()
mentioned in this article. So the OP's question could possibly be solved by this (that is, assuming the <div id="destination" />
does not yet exist, the following approach will create such a wrapper from scratch - the OP was not clear about whether the wrapper already exists or not):
$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')
It sounds promising. However, when I was trying to do $("[id^=row]").wrapAll("<fieldset></fieldset>")
on multiple nested structure like this:
<div id="row1">
<label>Name</label>
<input ...>
</div>
It correctly wraps those <div>...</div>
and <input>...</input>
BUT SOMEHOW LEAVES OUT the <label>...</label>
. So I ended up use the explicit $("row1").append("#a_predefined_fieldset")
instead. So, YMMV.
The .appendChild
does precisely that - basically a cut& paste.
It moves the selected element and all of its child nodes.
本文标签: javascriptHow to move an element into another elementStack Overflow
版权声明:本文标题:javascript - How to move an element into another element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736665338a1946631.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论