开发者

Removing children elements given an index?

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 a开发者_如何学Gobove for loop won't really work, but is the kind of thing I would do if there's no other way)


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

$("#parent").children().slice(N).detach();

If the elements are not going to be reinserted, use remove() instead of detach() in order to discard data and events associated with the removed elements.


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

$('#parent div:lt(2)').remove();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜