Take the 2-minute tour ×

I've got a layout like this:

<div id='parent'>

    <div id='row_0'></div>

    <div id='row_1'></div>

    <div id='row_2'></div>


    <div id='row_N'></div>

At some point, I want to remove all div "rows" above a certain index, like:

for (var index = 1; index < $('#parent').children.length; index++) {
    $('#parent').remove('#row_' + index);

is there a simpler way to do this in jquery? Something like 'just remove all children starting from index N'?

(the above for loop won't really work, but is the kind of thing I would do if there's no other way)

share|improve this question
add comment

3 Answers

up vote 9 down vote accepted

"Just remove (detach) all children of #parent, starting at element N":

share|improve this answer
+1 - This is the only answer that seems to do what OP wants (remove elements at and above the given index). Although, I'd only use .detach() if you're going to keep a reference to them and re-insert, or if you're certain there's no attached data. –  user113716 Aug 3 '10 at 20:12
...it's also the only answer that ensures that only direct descendants are considered. –  user113716 Aug 3 '10 at 20:17
@patrick, would I use remove() then instead of detach()? I don't need references to the removed divs anymore, and some of their children (elements within each row div) will have >data< in it. –  user246114 Aug 3 '10 at 21:29
Use remove(). "The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time." — api.jquery.com/detach –  You Aug 3 '10 at 21:38
@user - What I mean by data is any sort of information that jQuery directly associates with an element. Examples of when this occurs is when you attach event handlers, animate elements, or directly attach custom data. If you use .detach(), none of that data gets cleaned up. If you're unsure, use .remove(). This will remove all that data so it doesn't needlessly persist. –  user113716 Aug 3 '10 at 21:40
add comment

To remove rows 0 and 1 select rows less than 2 using the lt selector and then remove them:

$('#parent div:lt(2)').remove();
share|improve this answer
Oh I need to remove rows greater than an index - is it the same operation, just replace "lt" with "gt"? –  user246114 Aug 3 '10 at 20:07
@user246114 Yes. api.jquery.com/gt-selector –  Adam Aug 3 '10 at 20:44
One more thing: if you want to remove the element with known index use eq. Documentation here. –  Ionicã Bizãu Feb 12 '13 at 14:11
add comment

This is an old thread, but I'm curious* why nobody mentioned nth-child.

$("#parent > div:nth-child(n + " + index + ")").remove();

*Update: I didn't have enough rep to know it at the time, but there had been an nth-child answer, deleted.

share|improve this answer
add comment

Your Answer


