15

how do i move content from one hidden div to another displayed div using jquery?

say i have div1 with display style is none and another div "div2" with display style block.

how do I move the content from div1 to div2 and clear div1?

user384080
  • 4,576
  • 15
  • 64
  • 96
  • Where are you moving the content to specifically? Prepended or appended, in a specific target, etc.? – Chris Laplante Jul 14 '10 at 01:48
  • I found a good answer related to this question here: http://stackoverflow.com/questions/2792352/how-do-you-move-html-from-one-div-to-another-with-jquery-without-breaking-javasc – netusco Feb 02 '12 at 11:55

4 Answers4

22

.contents() may be what you need:

$('#div1').contents().appendTo('#div2')

Take note that it will move (not copy) the inner elements from one div to the other.

jbyrd
  • 5,287
  • 7
  • 52
  • 86
D.Tate
  • 2,289
  • 3
  • 22
  • 35
  • 2
    Not sure you need the surrounding $() - you can make it `$('#div1').contents().appendTo('#div2');` – jbyrd Jan 10 '17 at 21:09
  • @jbyrd that's quite possible... maybe someone can do a jsfiddle. Or feel free to just edit my post if you're pretty sure that works – D.Tate Jan 10 '17 at 23:35
  • 2
    Yes, I just confirmed it works without the extra $(). – jbyrd Jan 11 '17 at 02:11
11

Why not just show the hidden div and hide the displayed one?

But to answer your question.

 $('#div2').html($('#div1').html());
$('#div1').html('');
Stephen Wrighton
  • 36,783
  • 6
  • 67
  • 86
  • 1
    @ronald-yoh - Are you including jQuery in the page? when your question is tagged with jquery, there is an assumption you're using it. – Nick Craver Jul 14 '10 at 02:06
  • Small thing, but for the second line, use `.empty()` - more semantically explicit (and slightly faster). – jbyrd Jan 10 '17 at 21:05
0
$( $('#div1').html() ).appendTo('#div2')
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
0

First you'd need to get the HTML from DIV1, and then set the HTML in DIV2.

Use the get/set operations available on the .html() selector.

Like this:

var div1Html = $('#div1').html();
$('#div2').html(div1Html);
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • 1
    sounds like something else on your page. i created a simple page with nothing but two div's and the above code works fine (as does everyone else's similar answers) – RPM1984 Jul 14 '10 at 05:52
  • please note the form is on MVC framework.. it might behave differently.. thanks – user384080 Jul 14 '10 at 06:49
  • 2
    javascript/jquery deals with html and the DOM only (client-side), it has no bearing on what web server technology (web forms, mvc) – RPM1984 Jul 14 '10 at 12:15