I have some code that works fine but it's become too slow:
HTML:
I have a container that contains about 50 ul
elements. Each ul
element has a h4
heading followed by a series of li
elements. The function hides the heading if no line elements are visible.
Javascript/jQuery:
function show_or_hide_headings() {
$('#container').children('ul').each(function (i) {
var $this = $(this),
$h4 = $this.children(':first');
if ($this.children('li:visible').length) {
$h4.show();
} else {
$h4.hide();
}
});
}
It was working quite acceptably until I changed the nature of the li
elements. Each li
is now a mini table comprising <table><tr><td>icon</td><td>text</td></tr></table>
. It now takes 2 seconds to process, whereas it previously worked in less than half a second. (The table is there to stop the text wrapping under the icon.)
I confess I can't quite understand why adding the additional elements into each li
should slow down the DOM processing so much because I've used the .children
selector to only go one DOM layer deep.
I've also tried:
$('#container').find('h4').each(function (i) {
var $this = $(this);
if ($this.siblings('li:visible').length) {
$this.show();
} else {
$this.hide();
}
});
and $('#container').children().children('h4')
for good measure.
What is notable, too, is that when there are many li
elements visible, it is much slower than when few are visible. There are no more lines now, however, than when it worked quite quickly (i.e., before the table was put into each line).
Any advice greatly appreciated, but please don't request I post more code than I have :)
Thanks.
I suspect that determining if an element is visible or not is quite expensive. Consider instead adding and deleting a class to hide or show elements. Then you can select them directly based on the class, which will mostly be supported by a host getElementsByClassName or querySelectorAll method.
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