Experimenting some new ideas realized me some the difference between these functions. These functions are great way to copy or move objects in DOM but what if you want something specific. Have a look, what is the difference.
clone()
clone() is the function use to copy any object and put it somewhere is DOM. This copying and pasting could be more cool with appendTo, prependTo, before and after function look how.Markup
<div class='outer'>Well we know that using clone function we can copy the content but if I use the above mentioned function with it you will see the difference:
<span class='inner1'>Hello</span>
<span class='inner2'>Bye</span>
</div>
Using appendTo & prependTo: appendTo() adds the element as a last child in selected elements. Where prependTo() adds the element as first child in selected elements. So what if I copy inner1 into inner2.
$('.inner1').clone().appendTo('.inner2');Markup will be:
<div class='outer'>
<span class='inner1'>Hello</span>
<span class='inner2'>Bye<span class='inner1'>Hello</span></span>
</div>
With prependTo():
$('.inner1').clone().prependTo('.inner2');Markup will be:
<div class='outer'>
<span class='inner1'>Hello</span>
<span class='inner2'><span class='inner1'>Hello</span>Bye</span>
</div>
Using before & after: before() is a bit different, it adds the elements before the selected elements, where after adds the elements after the selected elements. If I clone inner2 and put it before inner1 then markup will be:
$('.inner2').clone().before('.inner1');Markup will be like be:
<div class='outer'>Same goes with after but it just add the element after the selected elements.
<span class='inner2'>Bye</span>
<span class='inner1'>Hello</span>
<span class='inner2'>Bye</span>
</div>
append()
append() adds the object inside the selected elements.Lets go for basic one, add element as the last child of the selected elements, but do you really know that you can shift or move one object in DOM using this function.
Using the same markup, lets shift inner1 after inner2.
<div class='outer'>
<span class='inner1'>Hello</span>
<span class='inner2'>Bye</span>
</div>
$('.inner1').append('.outer') ;New markup will be:
<div class='outer'>This one makes a great difference between append and clone, clone creates copy while append shifts the one.
<span class='inner2'>Bye</span>
<span class='inner1'>Hello</span>
</div>
appendTo()
appendTo() is quite similar to append, the major difference is in appendTo is that we select the elements to be added or shifted as a selector whereas in append we select the target in which the element to me added or to be shifted.
Post A Comment:
0 comments: