bobsoap
bobsoap

Reputation: 5104

Moving a DOM element with append()?

I have a div element like

<div id="move">Something</div>

...that I'd like to move from one position to another in the DOM. Can I do this with appendTo(), like so:

$('#move').fadeOut(500, function() {
   $(this).appendTo('#another-container').fadeIn(500);
});

...or will this duplicate it?

If it's being duplicated, there would be two elements with the same id in the DOM. How could I avoid this?

Upvotes: 9

Views: 11461

Answers (3)

Ilya Kushlianski
Ilya Kushlianski

Reputation: 968

You can do it with .append or .after or similar methods.

<ul class="list1">
  <li>You wanted to move this element!</li>
  <li>Element 2</li>
  <li>Element 3</li>
</ul>

<ul class="list2">
  <li></li>
  <li>Element 2</li>
  <li>Element 3</li>
</ul>

<button onclick="moveIt()">Move element</button>

So the code to move the first .li from .list1 to .list2 will be:

function moveIt() {
  var elementToBeMoved = $(".list1 li:first");
  $(".list2 li:first").append(elementToBeMoved);
}

Working pen

Upvotes: 0

Rob W
Rob W

Reputation: 348992

Yes, the appendTo method moves elements from the DOM tree. If you want to copy an element, .clone() is used.

Example:

Body:   <div>
           <a>Test</a>
        </div>
        <span></span>
jQuery code:
   $("a").appendTo("span");

After:  <div></div>
        <span>
           <a>Test</a>
        </span>

Upvotes: 16

jgasiorowski
jgasiorowski

Reputation: 1033

I took it directly from jQuery documentation http://api.jquery.com/append/

$( ".container" ).append( $( "h2" ) );

"If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):"

Upvotes: 6

Related Questions