jQuery .each() with multiple selectors - skip, then .empty() elements
I'd like to remove all matching elements, but skip the first instance of each match:
// Works as expected: removes all but first instance of .a
jQuery ('.a', '#scope')
.each ( function (i) {
if (i > 0) jQuery (this).empty();
});
// Expected: removal of all but first instance of .a and .b
// Result: removal of *all* instances .a and .b
jQuery ('.a, .b', '#scope')
.each ( function (i) {
if (i > 1) 开发者_JS百科jQuery (this).empty();
});
<div id="scope">
<!-- Want to keep the first instance of .a and .b -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<!-- Want to remove all the others -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<div class="a">[bla]</div>
<div class="b">[bla]</div>
...
</div>
Any suggestions?
- Using
jQuery()
rather than$()
because of conflict with 'legacy' code - Using
.empty()
because.a
contains JS I'd like to disable - Stuck with jQuery 1.2.3
Thanks you!
Give this a try:
$('.a:gt(0), .b:gt(0)').remove();
I'm not sure if combining them into one selector is possible with the :gt()
, it may change the scope and remove all of them after the first .a
.
It looks like your HTML is incorrect. I modified it to the following:
<div id="scope">
<!-- Want to keep the first instance of .a and .b -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<!-- Want to remove all the others -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<div class="a">[bla]</div>
<div class="b">[bla]</div>
...
</div>
Then this seemed to work:
jQuery('div#scope div.a').not(':first').empty();
jQuery('div#scope div.b').not(':first').empty();
精彩评论