With visibility:hidden, the element still takes up space. With display:none, it is effectively removed from the DOM. Hiding DOM elements with CSS is a common task.
The only difference is that detach() method keeps all the data associated with that removed element.
jQuery remove() Method The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.
hide() sets the matched elements' CSS display property to none . remove() removes the matched elements from the DOM completely. detach() is like remove() , but keeps the stored data and events associated with the matched elements.
I have a dropdown that contains around 100,000 rows which make up a list.
<input id="search" type="text" />
<ul>
<li>item 1</li>
<li>item 2</li>
...
<li>item 100,000</li>
</ul>
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 of 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 their any JavaScript experts who can see any problems with the code, or offer some optimization techniques?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With