A Mobin
A Mobin

Reputation: 148

How to detach and append to relevant div only jQuery

I am trying to detach the div from the relevant parent and then append to the same parent div.

//Jquery Code
jQuery(function(){
    moveColorDots();

});
function moveColorDots(){
    var copyDivData = jQuery('.variations_form.wvs-archive-variation-wrapper').detach();
    copyDivData.appendTo('.product-variations');
}
<div class="pp-content-post">
    <div class="variations_form wvs-archive-variation-wrapper">
      some data here
    </div>
    <div class="product-box">
        <div class="glasses-sec">
            <h3>title</h3>
        </div>
        <div class="product-variations"></div>
    </div>
</div>

Expected result. enter image description here

But after running the above code I am getting the following result. enter image description here

Upvotes: 1

Views: 765

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

.detach Description: Remove the set of matched elements from the DOM.

That means you append all the detached elements to every product-variations element ..So

  • You need to loop through the variations_form.wvs-archive-variation-wrapper elements by using .each()

  • Also you can use .appendTo() directly

//Jquery Code
jQuery(function(){
    moveColorDots();

});
function moveColorDots(){
    jQuery('.variations_form.wvs-archive-variation-wrapper').each(function(){
     var product_variations = jQuery(this).next('div').find('.product-variations');
     jQuery(this).appendTo(product_variations);
    });
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pp-content-post">
    <div class="variations_form wvs-archive-variation-wrapper">
      some data here 1
    </div>
    <div class="product-box">
        <div class="glasses-sec">
            <h3>title</h3>
        </div>
        <div class="product-variations"></div>
    </div>
</div>

<div class="pp-content-post">
    <div class="variations_form wvs-archive-variation-wrapper">
      some data here 2
    </div>
    <div class="product-box">
        <div class="glasses-sec">
            <h3>title</h3>
        </div>
        <div class="product-variations"></div>
    </div>
</div>

Note: This line of code var product_variations = jQuery(this).next('div').find('.product-variations'); is depending on your html structure it works for the posted html here .. But if you've another html structure you need to modify it to catch the desired element

Upvotes: 1

Related Questions