MOCKSTACKS
EN
Questions And Answers

More Tutorials









Jquery Caching Selectors


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');
nav.show();


This would replace:

$('#navigation').show();


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>
</div>
<script>
 var children = $('.child');
 var firstChildText = children[0].text();
 console.log(firstChildText);

 // output: "Child 1"
</script>


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');
$nav.show();


Conclusion

In this page (written and validated by ) you learned about Jquery Caching Selectors . What's Next? If you are interested in completing Jquery tutorial, your next topic will be learning about: Jquery Combining selectors.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.