Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .remove performance

I am trying to remove the li's with conditon under Ul in multiple div's.

<div>
    <ul>
        <li class="sel">.....</li>
        <li class="sel">.....</li>
         ............
        <li>.....</li>
        <li>.....</li>
         ...........
         <!-- I have some 600 li's -->
    </ul>
</div>

I have 200 li's with class='sel'. Now I need to remove the remaining 400 li's.

I am trying to remove in two ways, like,

$("ul", this).each(function(){
    $("li", this).each(function(){
        $(this).remove();
        //Also tried with -- $(this).empty().remove();
    });
});

other way like,

$("ul", this).each(function(){
    $("li[class!=sel]", this).remove(); // Also tried with 'not'
});

Now the problem is, When I am trying to execute these ways In IE getting Script overloaded error.

Please help me out on other ways to remove unwanted li's.

Note: I don't want to keep the un-wanted li's to hide() state.

Thanks in advance...

like image 968
Max Avatar asked Feb 07 '12 16:02

Max


3 Answers

If you're using the Attribute Not Equal Selector, you don't need to wrap it with .each() - simply call it like this:

$('li[class!="sel"]').remove();

The selector ('li[class!="sel"]') is grabbing all <li> elements that don't have class sel and then calling the remove() method on that entire set of elements.

Demo

Edit

If you only want to target the <ul> which contains the <li class="sel"></li> elements, you can set the context like this:

// Find the first <li> with class="sel" and get it's parent <ul>
var $ul = $('li.sel:first').parent('ul');

// Use $ul as the context for the removal of the <li> elements
$('li[class!="sel"]', $ul).remove();
like image 110
Colin Brock Avatar answered Nov 14 '22 19:11

Colin Brock


For what it's worth, I ran into a similar problem just a couple of weeks ago, only in IE8, even calling .remove() on a single item selected by id. The problem only occurred when the element contained a great deal of content.

What I did was to call .html('') to clear the element just before calling .remove(). This reduced the time dramatically (sub-second).

Mine was obviously a different situation (one element vs. many, selected by id vs. contextual selectors, not sure what your li content is, etc.), but it might be worth a shot.

$("ul", this).each(function(){
    $("li[class!=sel]", this).html('').remove();
});
like image 31
David Ruttka Avatar answered Nov 14 '22 19:11

David Ruttka


Try detaching the ul, remove the li's, then reattach the ul.

$("ul", this).detach().find("li").not(".sel").remove().end().end().appendTo(this);

This prevents the browser from redrawing until all li's that need to be removed are removed.

like image 1
Kevin B Avatar answered Nov 14 '22 19:11

Kevin B