Caching selectors using jquery

Each time you use a selector in jQuery the DOM is searched for elements that match your query. Doing this too often or repeatedly will decrease performance. If you refer to a specific selector more than once you should add it to the cache by assigning it to a variable: 

var nav $('#navigation');

This would replace: 


Caching this selector could prove helpful if your website needs to show/hide this element often. If there are multiple elements with the same selector the variable will become an array of these elements: 

<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
var children = $('.child');
var firstChildText = children[0].text();
// output: "Child 1"

NOTE: The element has to exist in the DOM at the time of its assignment to a variable. If there is no element in the DOM with a class called child you will be storing an empty array in that variable. 

<div class="parent"></div> <script> var parent = $('.parent'); var children = $('.child'); console.log(children); // output: [] parent.append('<div class="child">Child 1</div>'); children = $('.child'); console.log(children[0].text()); // output: "Child 1" </script>

Remember to reassign the selector to the variable after adding/removing elements in the DOM with that selector. 

Note: When caching selectors, many developers will start the variable name with a to denote that the variable is a jQuery object like so: 

var $nav $('#navigation');