Javascript - Fastest way to show and hide lots of list items

google-maps, javascript, jquery, performance

Solution

You could store the `<li>` elements in an array directly so you don't have to do hundreds of CSS selector lookups. Then instead of `$("ul#theList li#"+i)` you just do `liArray[i]`.

FYI, `"ul#theList li#<i>"` is equivalent to just `"#<i>"` since element IDs are (supposed to be) unique. You don't need the extra context.

Problem

As the user pans around a Google Map, a list of of currently visible markers is updated. This list contains up to 1000 items, and it slows down when several hundred li's are shown or hidden all at once. It's less than half a second, but it's getting annoying. An array (newLiList) contains the items which should now be visible. Another array (currentLiList) has the items which were previously visible. Both arrays contain the ids of the li's as indexes. ``` for (var i in newLiList) { if (currentLiList[i] != true) { $("ul#theList li#"+i).show(); } } for (var i in currentLiList) { if (newLiList[i] != true) { $("ul#theList li#"+i).hide(); } } ``` Is there a faster way to do this?

Original source