shadowbudz
shadowbudz

Reputation: 241

How to move element to another element in Jquery

Hi I would like to move this element into another element. Sample

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

into this

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

so I have something like this

<div id="destination">
  <div id="me-first"></div>
  <div id="source">...</div>
  <div id="last-here"></div>
</div>

Here is my code

jQuery(document).ready(function (){
        jQuery("#destination")
        .prependTo("#source");
    });

My problem is it will only transfer in the first place before me-first div. How do i put it in the middle of the me-first div and last-here div? Thanks

Here is the wrong placement after I ran my code.

<div id="destination">
  <div id="source">...</div>
  <div id="me-first"></div>
  <div id="last-here"></div>
</div>

Upvotes: 1

Views: 78

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388436

All of your elements have ID attributes, so use id selector(prefix #) to select them, not class selector(prefix .) which is used to select element by class name

jQuery(function($) {
  $("#source").prependTo("#destination");
});
div {
  padding: 5px;
  margin-bottom: 5px;
  border: 1px solid black;
  min-height: 10px;
}
#destination {
  border-color: red;
}
#me-first {
  border-color: green;
}
#last-here {
  border-color: blue;
}
#source {
  background-color: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="destination">
  <div id="me-first">
    <div id="source">
      ...
    </div>
    <div id="last-here">
    </div>
  </div>
</div>

Upvotes: 1

Derek
Derek

Reputation: 4751

Use .after():

jQuery('#me-first').after(jQuery('#source'));

This will place #source after #me-first in the DOM.

Upvotes: 1

Related Questions