This question already has answers here:
jQuery move node out of its parent
                                
                                    (3个答案)
                                
                        
                                4年前关闭。
            
                    
我正在尝试获取一个div(在本例中为“ childDiv2”)及其内容,并将其移至其父级之前。

所以从本质上来说

<div id="parentDiv">
   <div class="childDiv1">
     <div class="contents"></div>
     <div class="contents"></div>
     <div class="contents"></div>
   </div>
   <div class="childDiv2">
     <div class="contents"></div>
     <div class="contents"></div>
     <div class="contents"></div>
   </div>
</div>


并做到这一点

<div class="childDiv2">
  <div class="contents"></div>
  <div class="contents"></div>
  <div class="contents"></div>
</div>
<div id="parentDiv">
   <div class="childDiv1">
     <div class="contents"></div>
     <div class="contents"></div>
     <div class="contents"></div>
   </div>
</div>


我知道我可能需要使用.parent()和.before()才能使其正常工作,但我对jquery的外观有所了解。有任何想法吗?

最佳答案

您将使用.insertBefore() method

$('#parentDiv .childDiv2').insertBefore('#parentDiv');

08-17 14:03