简体   繁体   English

如何删除jQuery中第一个元素和第二个元素以外的所有元素?

[英]How to remove all element Except first element and Second element in jQuery?

HTML 的HTML

<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>

in Above HTML code i want to remove all element except <h3> and default content <div> inside the <div class='geo_select'> in jquery.. How to remove all element except first 2 element in jquery? 在上面的HTML代码中,我想删除jquery中<div class='geo_select'>内部的<h3>和默认内容<div>之外的所有元素。如何删除jquery中除前2个元素之外的所有元素? in my above scenario? 在上述情况下?

There are several ways to do that in jQuery 有几种方法可以在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()

Or with css, simply hide it. 或使用CSS,只需将其隐藏即可。

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

You can just use CSS if you want. 您可以根据需要使用CSS。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM