10

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.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
sean
  • 101
  • 1
  • 1
  • 4

2 Answers2

12

You could do

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

Or

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

davin
  • 44,863
  • 9
  • 78
  • 78
  • @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. – T.J. Crowder Jul 22 '11 at 12:16
  • 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 Jul 22 '11 at 12:19
  • Or if you want it to go just before hand, use `$('#example').insertBefore('#wrapper');` – phyatt Feb 19 '18 at 22:18
7

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.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • 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? – sean Jul 22 '11 at 12:25
  • @sean: No unless it hasn't been inserted in the DOM just yet. – Robert Koritnik Jul 22 '11 at 12:26
  • It has been inserted and I made sure to include your code after the other one. What could be wrong? – sean Jul 22 '11 at 12:27
  • @sean: are you maybe loading your original `#wrapper` content asynchronously using Ajax call? – Robert Koritnik Jul 22 '11 at 12:31
  • @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). – Robert Koritnik Jul 22 '11 at 12:34
  • I am inserting a video player just like the one on this site: http://mysteryguitarman.com/ ...with your code, i am trying to rearrange the dom. i'm not sure if that's ajax. – sean Jul 22 '11 at 12:35
  • @Sean: If you're just trying to reposition existing elements, then it's not Ajax. – Robert Koritnik Jul 24 '11 at 09:33