patternjavascriptMinor
Fastest way to remove/hide a lot of elements from a list
Viewed 0 times
elementswaylotremovefastestlistfromhide
Problem
I have a dropdown that contains around 100,000 rows which make up a list.
I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not match. This is the class I wrote to perform the removing of list elements.
See the fiddle (list has about 2000 items)
I am just adding a class which adds a
Are there any JavaScript experts who can see any problems with the
item 1
item 2
...
item 100,000
I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not match. This is the class I wrote to perform the removing of list elements.
See the fiddle (list has about 2000 items)
// requires jQuery
var Search = (function(){
var cls = function (name) {
var self = this;
self.elem = $('#' + name);
self.list = $('#' + name).next('ul').children();
self.elem.bind('keyup', function () { self.change(); });
};
cls.prototype = {
change: function () {
var self = this;
// gets the closest ul list
var typed = self.elem.val();
// only do something if there is something typed
if (typed !== '') {
// remove irrelevent items from the list
self.list.each(function () {
var item = $(this).html();
if (item.indexOf(typed) === -1) {
$(this).addClass('zero');
// tried using a class with visibility hidden
} else {
$(this).removeClass('zero');
}
});
} else {
// check what list items are 'hidden' and unhide them
self.list.each(function () {
if ($(this).hasClass('zero')) {
$(this).removeClass('zero');
}
});
}
}
};
return cls;
}());I am just adding a class which adds a
height: 0, and no margin, padding, etc, but I have also tried using visibility: hidden. I have also tried using the detach method in jQuery but this is about the same in terms of speed. Are there any JavaScript experts who can see any problems with the
Solution
A couple notes:
-
-
As far as optimization goes, one thing you could do is iterate the list items and store all the strings in an array as part of the initialization for your function. Then when you're iterating
-
display: none does everything you're trying to do with your existing CSS class; it hides and completely removes the element from the layout. So instead of adding the zero class you would set display to none, and instead of removing it you would set display to block.-
As far as optimization goes, one thing you could do is iterate the list items and store all the strings in an array as part of the initialization for your function. Then when you're iterating
self.list, fetch the string from your cached array with the current index instead of calling $(this).html(). That would most likely be faster because it eliminates a DOM lookup.Context
StackExchange Code Review Q#19763, answer score: 5
Revisions (0)
No revisions yet.