jQuery 搬移區塊

Posted in :

這個技能滿實用的, 有時候想移動div 到特定位置, 或是固定搬到最後一個,

$(this).insertAfter(target_div);

解法: How to move an element after another element using JS or jquery?
https://stackoverflow.com/questions/14549125/how-to-move-an-element-after-another-element-using-js-or-jquery

舉例:

I would like to move one DIV element beside another, it is normally like this:

<div class="box-content-top">
 <div class="box-related-product-top">
  <div>  

    <div class="price">
      ...   
    </div>              
    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="cart">
     ...
    </div>


   <div>  

    <div class="price">
      ...   
    </div>            
    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="cart">
     ...
    </div>

  </div>
</div>

I want to change the position of the div with the class .price to be after the .name class, to look like this:

<div class="box-content-top">
 <div class="box-related-product-top">
  <div>  

    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
     <div class="price"> // HERE
      ...   
    </div> 
    <div class="cart">
     ...
    </div>


   <div>  

    <div class="image">
     ...
    </div>
    <div class="name">
     ...
    </div>
    <div class="price"> // HERE
      ...   
    </div> 
    <div class="cart">
     ...
    </div>

  </div>
</div>

解法:

You can use insertAfter to move the element. Docs

$('.price').each(function() {
    $(this).insertAfter($(this).parent().find('.name'));
});

這個解法有一個限制,就是在搬家的時候,無法把自己的孫子節點搬成自己小孩節點,會顯得示錯誤訊息:

jquery-3.6.3.min.js:2 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *