简体   繁体   中英

Remove children element jquery

I have a list children element about >50 value:

<div class="parent">
   <div class="children"></div>
   <div class="children"></div>
   ...
   <div class="children"></div>
</div>

Now, I want to remove children eq from 1 to 30. Can you help me anyway to solve this problem quickly? Thank you very much.

You can try with jQuery's :lt() selector:

Select all elements at an index less than index within the matched set.

$('.parent > .children:lt(30)').remove(); //Remove the first 30

Demo:

 $('.parent >.children:lt(2)').remove(); // Remove the first 2
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <div class="children">1</div> <div class="children">2</div> <div class="children">3</div> </div>

In pure javascript, you have to use loop:

 var c = document.querySelectorAll(".children"); c.forEach(function (v,i){ if(i<2){ document.body.removeChild(v); } });
 <div class="children">1</div> <div class="children">2</div> <div class="children">3</div>

That's why it is better to use jQuery because you save many lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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