views:

365

answers:

2

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) 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!

+2  A: 

Give this a try:

jQuery ('.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.

Joseph Silvashy
It _is_ possible to use `:gt()` with a combined selector:`jQuery ('.a:gt(0), .b:gt(0)').empty()` works well.Are you able to suggest why my approach wasn't working?Thank you!
joe
Oh no, you're right I tried that and yours is working fine as well. **Edited my answer**.
Joseph Silvashy
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();
Bryson
HTML typo was only in my simplified example.Thanks for your suggestion!
joe