jQuery .each() with multiple selectors - skip, then .empty() elements
Posted
by joe
on Stack Overflow
See other posts from Stack Overflow
or by joe
Published on 2010-03-19T21:50:17Z
Indexed on
2010/03/19
21:51 UTC
Read the original article
Hit count: 673
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!
© Stack Overflow or respective owner