2016-04-22 80 views
0

我想刪除所有類'toBeRemoved'的div,我不太清楚如何去做。我研究瞭解包裝,但一直沒有能夠接近我正在尋找的東西。jquery解開多個遞歸節點

是否可以很容易地從這個去:

<div class="toBeRemoved"> 
    <div class="toBeRemoved"> 
     <table> 
      <tbody> 
       <tr> 
        <td> 
         <div class="toBeRemoved"> 
          <div class="toBeRemoved"> 
           <div style="text-align: left;"> 
            <div class="toBeRemoved"> 
             <div class="toBeRemoved"> 
              First node 
             </div> 
            </div> 
           </div> 
          </div> 
         </div> 
        </td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
    <div class="toBeRemoved"> 
     <table> 
      <tbody> 
       <tr> 
        <td> 
         <div class="toBeRemoved"> 
          <div class="toBeRemoved"> 
           <div style="text-align: left;"> 
            <div class="toBeRemoved"> 
             <div class="toBeRemoved"> 
              Second node. 
             </div> 
            </div> 
           </div> 
          </div> 
         </div> 
        </td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
</div> 

<table> 
    <tbody> 
     <tr> 
      <td> 
       <div style="text-align: left;"> 
        This needs to be kept 
       </div> 
      </td> 
     </tr> 
     </tbody> 
    </table> 
    <table> 
     <tbody> 
     <tr> 
      <td> 
       <div style="text-align: left;"> 
        This needs to be kept 
       </div> 
      </td> 
     </tr> 
     </tbody> 
</table> 
+0

哪裏是'這需要在原有的HTML被kept' ? – Barmar

回答

2

替換每個.toBeRemoved元素與它的直接孩子:

$('.toBeRemoved').each(function() { 
    $(this).replaceWith($(this).children()); 
}); 

Fiddle

+0

太棒了,正是我需要的,謝謝先生! – user3800174

1

.remove()將無法​​工作。因爲它會移除孩子。

var cnt = $(".toBeRemoved").contents(); 
$(".toBeRemoved").replaceWith(cnt); 

從這裏開始。 How to remove only the parent element and not its child elements in JavaScript? 重複發佈。

編輯應該申請職位

$(".toBeRemoved").each(function() { 
    var cnt = $(".toBeRemoved").contents(); 
    $(".toBeRemoved").replaceWith(cnt); 
}); 
+0

循環是不必要的。 – JJJ

+0

確實。你確實嘗試過使用'.remove'是的? – Stuart

+0

@Juhana我擺脫了循環。謝謝 – Radmation