Move a div somewhere else in the dom

12,715

Solution 1

You could do

$('#wrapper').prepend( $('#example') );

Or

$('#example').prependTo('#wrapper');

Solution 2

The other way around with selectors

$("#example").prependTo("#wrapper")

Here's a JSFiddle example to prove that it works as expected. If this code doesn't seem to work in your case, than compose your own JSFiddle so we can actually see what's wrong with your code.

Share:
12,715
sean
Author by

sean

Updated on June 27, 2022

Comments

  • sean
    sean almost 2 years

    The following code gets dynamically inserted into the DOM. However, I'd like to move div#example from where it is and prepend it to #wrapper. How can I use jQuery to achieve this?

    <div id="wrapper">
         <div id="div1">
              <div id="example">
              </div>
         </div>
         <div id="div2">
    
         </div>
    </div>
    

    I tried $('#wrapper').prepend('#example');

    But that just adds the text #example (not the div) into #wrapper.

  • T.J. Crowder
    T.J. Crowder over 12 years
    @sean: The reason davin's first works where yours doesn't is that jQuery has no way of knowing that your '#example' isn't text you want prepended to the wrapper div. By passing in a jQuery object instead, we make sure it knows what it's supposed to do.
  • sean
    sean over 12 years
    I'm sure the code given here is correct but both of these don't seem to work for me. Could the reason be because #wrapper is itself being dynamically inserted on page load? If so, how do I get around that?
  • sean
    sean over 12 years
    I'm sure this one is also correct but it doesn't work for me. Could the reason be because #wrapper is itself being dynamically inserted on page load?
  • Robert Koritnik
    Robert Koritnik over 12 years
    @sean: No unless it hasn't been inserted in the DOM just yet.
  • sean
    sean over 12 years
    It has been inserted and I made sure to include your code after the other one. What could be wrong?
  • Robert Koritnik
    Robert Koritnik over 12 years
    @sean: are you maybe loading your original #wrapper content asynchronously using Ajax call?
  • Robert Koritnik
    Robert Koritnik over 12 years
    @sean: well if you don't I really suggest you put together a simplified example of your code just to prove it doesn't work in your case. Don't put in too much insignificant details (none would be perfect).
  • sean
    sean over 12 years
    I am inserting a video player just like the one on this site: mysteryguitarman.com ...with your code, i am trying to rearrange the dom. i'm not sure if that's ajax.
  • Robert Koritnik
    Robert Koritnik over 12 years
    @Sean: If you're just trying to reposition existing elements, then it's not Ajax.
  • phyatt
    phyatt about 6 years
    Or if you want it to go just before hand, use $('#example').insertBefore('#wrapper');