2016-01-21 46 views
2

例如說我有以下標記一個HTML元素的特定祖先:得到使用jQuery

<article> 
    <div class="container"> 
     <h2>Article Title</h2> 
     <p>Lorem Ipsum...</p> 
     <div class="details"> 
      <span class="category-info">X</span> 
      <ul> 
       <li>One</li> 
       <li>Two</li> 
       <li>Three</li> 
      </ul> 
     </div> 
    </div> 
</article> 

<article> 
    <div class="container"> 
     <h2>Article Title</h2> 
     <p>Lorem Ipsum...</p> 
     <div class="details"> 
      <ul> 
       <li>One</li> 
       <li>Two</li> 
       <li>Three</li> 
      </ul> 
     </div> 
    </div> 
</article> 

,我想刪除它包含一個.category-info

$(".category-info").parent().parent().parent().remove(); 

任何物品是否有比撥打.parent().parent().parent()向上移動DOM更好的方法是什麼?

回答

2

更好的方法是使用:has() selector,以選擇具有.category-info後代元素article元素:

$('article:has(.category-info)').remove(); 

或者,您也可以使用.closest() method,避免鏈接的.parent()方法多次:

$('.category-info').closest('article').remove(); 

這將選擇最接近的article元素的祖先。

1

使用jQuery的has()像API下面的代碼:

$('article').has('.category-info').remove(); 

您可能需要閱讀本.has()

0

您可以使用jQuery closest

$(".category-info").closest("article").remove();