2017-02-13 151 views
1

HTML如何刪除所有元素除jQuery中的第一個元素和第二個元素?

<div class="geo_select"> 
     <h3>header 3</h3> 
     <div class="row form-group"> 
     default content 
     </div> 
     <div class="row form-group"> 
     //Dynamic content 1 here 
     </div> 
    <div class="row form-group"> 
     //Dynamic content 2 here 
     </div> 

    </div> 

在上面的HTML代碼我要刪除所有元素,除了<h3>和jQuery中的<div class='geo_select'>內默認的內容<div>。如何刪除所有元素除了在jQuery的第一個2元?在我上面的場景?

+0

給所有的動態內容一個額外的類,並刪除所有的div元素與那個class.Won't更容易? – Visrozar

回答

2

如果需要,您可以使用CSS。

.geo_select > div:not(:first-of-type) { 
    display:none; 
} 
4

有幾種方法可以做到,在jQuery的

// use this, if there are different types of elements as child 
$('.geo_select > div:nth-of-type(n+3)').remove() 

// use any of these if childs are same 
$('.geo_select > div:nth-child(n+3)').remove() 
$('.geo_select > div:gt(2)').remove() 

// this is jQuery way which reduce the set into the range 
$('.geo_select > div').slice(2).remove() 

或者利用CSS,只是將其隱藏。

.geo_select > div:nth-of-type(n+3){ 
    display:none; 
} 
+1

謝謝你@Pranav C Balan –

相關問題