开发者

Removing divs using jQuery after index N

开发者 https://www.devze.com 2023-03-31 00:57 出处:网络
Markup: <div id=\"status\"> <div style=\"display: block;\">Status OK - 16:57:09.</div>

Markup:

<div id="status">
    <div style="display: block;">Status OK - 16:57:09.</div>
    <div style="display: block;">Status OK - 16:57:09.</div>
    <div style="display: block;">Status OK - 16:57:05.</div>
    <div style="display: block;">Status OK - 16:57:05.</div>
    <div style="display: block;">Status OK - 16:57:03.</div>
    <div>No status yet.</div>
</div>

Using AJAX, I'm adding a new Div to the status div. I only want five divs to be inside at all time. Meaning after the sixth ajax class, the last div should be removed.

Here is my jQuery code:

<script type="text/javascript">
    function Update() {
        PurgeOldStatuses();
        $("#status").children().first().hide().fadeIn();
    }

    function PurgeOldStatuses() {
        // From the status div, find all divs with index after 5, and remove them.
        $("#status").$("div:gt(5)").remove();
    }
</script>

I wrote in a comment to illustrate what I think is开发者_Go百科 going on, perhaps I'm wrong.

Currently not elements are removed. Any suggestions why?


In order to get better performance, avoid proprietary selectors like :gt(), and only use valid CSS selectors.

This should be very quick:

$("#status").find("div").slice(5).remove();

or this:

$("#status div").slice(5).remove();

From the docs for the gt-selector[docs]:

Because :gt() is a jQuery extension and not part of the CSS specification, queries using :gt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(index) instead.

Note that the docs recommend using the slice()[docs] method, which grabs all elements in the set starting at the zero-based index you provide.


$("#status").find("div:gt(4)").remove();

Start with the element #status, then find looks for all descendants (of #status) matching the selector div:gt(4). Then remove gets rid of them.

The reason it's 4 (not 5), is that javascript is zero-based - the first element is 0. Thanks to Mark for pointing this out.

The genius of jQuery is chaining - each function in the chain returns the set of elements it was passed, so you can 'drill down'


This line is wrong:

 $("#status").$("div:gt(5)").remove();

should be:

 $("#status").find("div:gt(4)").remove();

EDIT: $ is not a property or method of the jQuery object, but find is a method on the object returned by the function $().


 $("#status > div:gt(5)").remove();


To leave 5 child div's with the shortest selector:

$("#status>div:gt(4)").remove(); 
0

精彩评论

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