Best way of using jQuery Selector

Nov 28, 2011 Posted by Lara Kannan
It is pretty important to understand how to write efficient element selection statement. One has to be very careful while jQuery selector statement. Below are some tips on how to use your jQuery selectors efficiently.

1. Always try to use ID as selector

You can use ID as selector in jQuery. See below jQuery code.
$("#elmID");
When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element. When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

2. Use class selector with tags

You can use CSS classes as selector. For example, to select elements with "myCSSClass" following jQuery code can be used.
$(".myCSSClass");
As said earlier, when classes are used DOM traversal happens. But there could be a situation where you need to use classes as selector. For better performance, you can use tag name with the class name. See below
$("div.myCSSClass");
Above jQuery code, restricts the search element specific to DIV elements only.

3. Keep your selector simple, don't make it complex

Avoid complex selectors. You should use make your selectors simple, unless required.
$("body .main p#myID em");
Instead of using such a complex selector, we can simplify it. See below.
$("p#myID em");

4.Don't use your selector repeatedly.

See below jQuery code. The selectors are used thrice for 3 different operation.
$("#myID").css("color", "red"); $("#myID").css("font", "Arial"); $("#myID").text("Error occurred!");
The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.
$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");

5.Know how your selectors are executed

Do you know how the selectors are executed? Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
$("p#elmID .myCssClass");

Hope this will help you. Happy coding!!!!

Share
Labels: ,

Post a Comment