- jQuery provides wide range of selectors to use and explore.
- Using these selectors we can select DOM elements and can traverse and manipulate then using jQuery methods.
- In this article we will see how to use jQuery selectors efficiently that also helps gaining optimization.
Following are the points to remember :
Use Id selector :
Always try to use ID selector while selecting a single element. The ID attribute is always unique on page, so browser finds it easy to select an element using ID slector.
The "#" symbol signifies that we are using id selector.
Avoid class selector alone :
Lets have a scenario. Suppose you have number of DIV elements on page with particluar class applied to it. You can select these div elements using class selector in below two ways.
eg 2: Efficient way
For first example, the browser will search all the elements on the page. For second example, the browser will select all the div elements and then filters it using the class selector.
So when you know which element to select with particular class, always use combination of element and class selector.
Be Specific and Simple :
Write the simple and specific selector query. Always try to query the element you want to select instead of quering their parents to reach thier target child.
$("body #myDiv #myP em ").css("color","red");
eg 2: Efficient way
eg 3: Another more efficient way
Increase Specificity from left to right :
Be specific while using selectors. Always use selector combination which searched less for elements. Consider the below example :
In above example, all em elements on page are selected and loaded to stack and then the selected elements are filtered based on "#myP". So instead, you can select all "#myP" element first and then search for em elements inside that. The above query will be less efficient when page has many em elements.
The following query is much better and more efficient.
Avoid repetition and Utilize chaining
Lets have a scenario where you want to perform multiple operations on selected div element.
In such cases do not select div element number of times equal to operations need to perfom.
Instead use chaining feature of jquery which allows to perform consecutive operations on set of selected elements one after another.
eg : Wrong way
eg : Efficient way
Thus the chaining helps in optimizing the selection process
Thus following above steps we can achieve efficient selector usage and optimization.