Jak przenieść element do innego elementu?

Chciałbym przenieść jeden element DIV do innego. Na przykład, chcę przenieść to (w tym wszystkie dzieci):

<div id="source">
...
</div>

Do tego:

<div id="destination">
...
</div>

Tak, że mam to:

<div id="destination">
  <div id="source">
    ...
  </div>
</div>
Author: BoltClock, 2009-08-15

13 answers

Możesz użyć appendTo funkcja (która dodaje do końca elementu):

$("#source").appendTo("#destination");

Alternatywnie możesz użyć prependTo funkcja (która dodaje do początku elementu):

$("#source").prependTo("#destination");

Przykład:

$("#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>
 1605
Author: Andrew Hare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-26 00:32:45

Moje rozwiązanie:

Ruch:

jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')

Kopia:

jQuery("#NodesToMove").appendTo('#DestinationContainerNode')

Zwróć uwagę na użycie .detach (). Podczas kopiowania należy uważać, aby nie powielać identyfikatorów.

 792
Author: Alejandro Illecas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-22 09:29:18

Właśnie użyłem:

$('#source').prependTo('#destination');

Które wziąłem z tutaj .

 105
Author: kjc26ster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-24 14:55:51

Jeśli div gdzie chcesz umieścić swój element ma zawartość wewnątrz i chcesz, aby element wyświetlał po główną treść:

  $("#destination").append($("#source"));

Jeśli div gdzie chcesz umieścić swój element ma zawartość wewnątrz, a chcesz pokazać element przed główną treść:

$("#destination").prepend($("#source"));

Jeśli div gdzie chcesz umieścić swój element jest pusty, lub chcesz zastąpić CAŁKOWICIE:

$("#element").html('<div id="source">...</div>');

Jeśli chcesz powielić element przed którymkolwiek z powyżej:

$("#destination").append($("#source").clone());
// etc.
 85
Author: sbaaaang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-22 23:05:38

A co z rozwiązaniem JavaScript ?

Zadeklaruj fragment:

var fragment = document.createDocumentFragment();

Dołączenie żądanego elementu do fragmentu:

fragment.appendChild(document.getElementById('source'));

Dołączenie fragmentu do pożądanego elementu:

document.getElementById('destination').appendChild(fragment);

Zobacz też

 68
Author: Ali Bassam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-15 20:04:53

Możesz użyć:

Aby Wstawić Po,

jQuery("#source").insertAfter("#destination");

Aby wstawić wewnątrz inny element,

jQuery("#source").appendTo("#destination");
 27
Author: Subrahmanyam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-24 11:00:42

Nigdy nie próbowałem zwykłego JavaScript... destination.appendChild(source); ?

onclick = function(){ destination.appendChild(source); }
div{ margin: .1em; } 
#destination{ border: solid 1px red; }
#source {border: solid 1px gray; }
<!DOCTYPE html>
<html>

 <body>

  <div id="destination">
   ###
  </div>
  <div id="source">
   ***
  </div>

 </body>
</html>
 19
Author: Bekim Bacaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-23 13:44:19

Możesz użyć następującego kodu, aby przenieść źródło do miejsca przeznaczenia

 jQuery("#source")
       .detach()
       .appendTo('#destination');

Spróbuj pracować 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>
 16
Author: Subodh Ghulaxe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-02 08:49:15

Jeśli chcesz uzyskać szybkie demo i więcej szczegółów na temat przenoszenia elementów, wypróbuj ten link:

Http://html-tuts.com/move-div-in-another-div-with-jquery


Oto krótki przykład:

Aby przesunąć nad elementem:

$('.whatToMove').insertBefore('.whereToMove');

Aby poruszać się po elemencie:

$('.whatToMove').insertAfter('.whereToMove');

Aby poruszać się wewnątrz elementu, przede wszystkim wewnątrz tego kontenera:

$('.whatToMove').prependTo('.whereToMove');

Aby poruszać się wewnątrz elementu, po wszystkich elementach wewnątrz tego kontenera:

$('.whatToMove').appendTo('.whereToMove');
 15
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-17 22:03:13

Stare pytanie, ale dotarło tutaj, ponieważ muszę przenieść zawartość z jednego kontenera do drugiego łącznie ze wszystkimi słuchaczami zdarzeń .

JQuery nie ma na to sposobu, ale robi to standardowa funkcja dom appendChild.

//assuming only one .source and one .target
$('.source').on('click',function(){console.log('I am clicked');});
$('.target')[0].appendChild($('.source')[0]);

Użycie appendChild usuwa .źródło i umieszcza go w celu, w tym jego słuchaczy zdarzeń: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild

 10
Author: HMR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-24 04:06:40

Możesz również spróbować:

$("#destination").html($("#source"))

Ale to całkowicie nadpisze wszystko, co masz w #destination.

 5
Author: Tamas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-24 14:41:09

Zauważyłem ogromną wyciek pamięci i różnicę wydajności między insertAfter & after lub insertBefore & before .. Jeśli masz mnóstwo elementów DOM lub musisz użyć after() lub before() wewnątrz zdarzenia MouseMove, pamięć przeglądarki prawdopodobnie wzrośnie i następne operacje będą działać bardzo wolno. Rozwiązaniem, którego właśnie doświadczyłem, jest użycie inserBefore zamiast before () I insertAfter zamiast after ().

 4
Author: spetsnaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-23 21:24:52

Ze względu na kompletność, istnieje inne podejście wrap() lub wrapAll() wymienione w w tym artykule . Tak więc pytanie OP może być rozwiązane przez to (to znaczy, zakładając, że <div id="destination" /> jeszcze nie istnieje, następujące podejście stworzy taką owijkę od zera - OP nie było jasne, czy owijka już istnieje, czy nie):

$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')

Brzmi obiecująco. Jednak kiedy próbowałem zrobić $("[id^=row]").wrapAll("<fieldset></fieldset>") na wielu zagnieżdżonych strukturach jak to:
<div id="row1">
    <label>Name</label>
    <input ...>
</div>

Poprawnie owija te <div>...</div> i <input>...</input>, ale jakoś pomija <label>...</label>. Więc zamiast tego użyłem jawnego $("row1").append("#a_predefined_fieldset"). Więc, YMMV.

 0
Author: RayLuo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-04 07:18:14