Something... that I would like to move from one positio...">

Moving a DOM element using append ()?

I have a div element like

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

... that I would like to move from one position to another in the DOM. Can I do this with appendTo() , for example:

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

... or does it duplicate it?

If it is duplicated, there will be two elements in the DOM with the same id . How could I avoid this?

+6
source share
3 answers

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

Example:

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

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

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

"If an element selected in this way is inserted in one place in another place of the DOM, it will be moved to the target (not cloned):"

+2
source

You can do this using .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); } 

Work pen

0
source

Source: https://habr.com/ru/post/902330/


All Articles