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.
h4
element is followed by theul
containing onlyli
items. I'm not sure about the CSS-not-table solution, though. I want wrap, but only within its own column (so nowrap is not suitable, I think). – Nick Jul 10 '12 at 6:38