简体   繁体   中英

How can I get every element except the last one with jQuery

I have several divs

<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

that are being generated dynamically. When the button is clicked, I need to remove all divs with myClass class except the last one. So far I have tried some variations of:

$('.myClass').not($('.myClass').last()).remove();

OR

$('.myClass').not($(this).last()).remove();

neither seem to work. What am I doing wrong?

尝试这种方式:

 $('.myClass:not(:last)').remove();

your code is running fine with no problems

You need to put it in $(document).ready();

here is demo https://jsfiddle.net/8w2jb1Lr/

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