tags:

views:

40

answers:

2

Hi,

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

Thanks

+2  A: 

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

$("#parent").children().slice(N).detach();
You
+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`.
patrick dw
...it's also the only answer that ensures that only direct descendants are considered.
patrick dw
@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.
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." — http://api.jquery.com/detach/
You
@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.
patrick dw
+3  A: 

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

$('#parent div:lt(2)').remove();
Adam
Oh I need to remove rows greater than an index - is it the same operation, just replace "lt" with "gt"?
@user246114 Yes. http://api.jquery.com/gt-selector/
Adam