remove 3 last divs with jQuery
Asked Answered
H

1

13
<div id="widgetAreaFooter">
<div class="row">1</div>
<div class="row">2</div>
<div class="row">3</div>
<div class="row">4</div>
<div class="row">5</div>
<div class="row">6</div>
<div class="row">7</div>
</div>

How to remove the 3 last div ?

I tryed this but it doesn't work :/

var row = $( '#widgetAreaFooter>.row' );
var nbr = row.length ;

for ( var i=4;i<nbr;i++ ) row.get(i).remove();
or
for ( var i=4;i<nbr;i++ ) row[i].remove();
Hobnob answered 8/7, 2011 at 10:52 Comment(1)
I guess the code you supplied only removed row 5 and 7. You also needed to i-- after (or during) removal: $(row[i--]).remove();. However @bazmegakapa's is clearer and safer. Edit: my mistake. You should also decrease nbr after removing the item. As I said, @bazmegakapa had the best solution.Cenesthesia
D
47

This will remove the last three elements:

$('#widgetAreaFooter > .row').slice(-3).remove();

jsFiddle Demo

  • You can get a part of a jQuery collection using .slice().

    If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning.

Dube answered 8/7, 2011 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.