Search code examples
javascripthtmljqueryappenddetach

jQuery().detach().appendTo Duplicating all detached elements


I'm trying to add some extra divs to the build-in blogs "read more" links. I've managed to add all the necessary div but I'm struggling to move the text from where it is into another div. I've managed to move it using:

'''jQuery(".readmore").detach().appendTo('.js-add-btn-assets');'''

But instead of moving the one .readmore element to the .js-add-btn-assets. Its making copies of all of the Read More Links on the page and putting them all under the .js-add-btn-assets so I essentially have 4 .readmore elements for every Read More link.

enter image description here

How do I change this so the .readmore class is only moving to the .js-add-btn-assets within its respected parent class instead of all classes on the page? Like this:

enter image description here

Here all the code I'm currently using

<span class="more-link">
  <a href="#" class="readmore">Continue reading
    <span class="screen-reader-text">Blog Template</span>
  </a>
</span>
var AddButtonWrap = document.querySelectorAll(".more-link");
    for (i = 0; i < AddButtonWrap.length; i++) {
                AddButtonWrap[i].classList.add("dbtb-button-wrap add-dbtb-button-div");
        }
    
var SelectButtonDiv = document.querySelectorAll(".add-dbtb-button-div"); {
    for (i = 0; i < SelectButtonDiv.length; i++) {  
        var dbtbBtnDiv = document.createElement('div');
        dbtbBtnDiv.className = 'dbtb-button js-add-btn-assets';
        SelectButtonDiv[i].appendChild(dbtbBtnDiv);
        }
    }
        
jQuery(".readmore").detach().appendTo('.js-add-btn-assets');

Solution

  • Do the moves in a third loop. Something like below should work (untested) First detach, then Append.

    for (i = 0; i < AddButtonWrap.length; i++)
    {
        var readMore = jQuery(AddButtonWrap[i]).find(".readmore").detach();
        readMore.appendTo(jQuery(AddButtonWrap[i]).find(".js-add-btn-assets"));
    }