Performance tips when selecting in jQuery

by Andreas Nylin 29. May 2009 20:31
1. Always use ID to select an element if you can. This is the fastest way to select elements.


2. Avoid selecting elements by class name.
Selecting with class name only will make jQuery search every element in the entire page. If you need to select elements by classname then use the element tag combined with the class name.

Avoid this: jQuery(".ElementClass")

Do this: jQuery("div.ElementClass")


3. Narrow it down. For example, if you know that the elements you want to select are in the top menu of the page then specify it when selecting.

jQuery("#TopMenu").find("li.MenuItem");

4. Avoid selecting the same element more than once. Store your selected element or use chaining.

Avoid this:

jQuery("#MyElement").addClass("SelectedItem");
jQuery("#MyElement").show();


Do this:

jQuery("#MyElement").addClass("SelectedItem").show();

Or this:

var myElement = jQuery("#MyElement");
myElement.addClass("SelectedItem");
// some more code...
myElement.show();

Tags: ,

Development

blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.