jQuery .each() with multiple selectors - skip, then .empty() elements
- by joe
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 of both .a and .b
jQuery ('.a, .b', '#scope')
.each ( function (i) {
if (i > 1) jQuery (this).empty();
});
<div id="scope">
<!-- Want to keep the first instance of .a and .b -->
<div class="a">[bla]</span>
<div class="b">[bla]</span>
<!-- Want to remove all the others -->
<div class="a">[bla]</span>
<div class="b">[bla]</span
<div class="a">[bla]</span>
<div class="b">[bla]</span
...
</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!