Here is an example of the type of code you shouldn’t write, but that I have seen many times. It needs to make multiple changes to some element(s) and performs the query selector each time it is needed.
You can ‘cache’ the response of queries you know you’ll use again in a variable however. Then each time you need to operate on those elements you just use the variable your assign them to. If there are queries you would use in multiple places in your app it can be a good idea to cache many queries at the start of your app so that you can reference them later.
Another good common practice is to prefix your cached variables with a `$` (like $ with jQuery) to indicate that it is a query response. I follow this pattern even when I don’t use jQuery as seen in the example above.
Another reason to use cached queries is that you can perform queries on all of the child elements of that element. Suppose you have a form and you will be working with many of the fields in the form to validate and submit the form. In this scenario I will typically query for the form first and then find the child elements of the form. In the example below it means instead of looking at every `input` on the page and checking whether it is a descendent of `.myForm` it will just look at the input fields that are child elements of `.myForm`.
The best way to manage caching of your queries though is to make the computer do it for you automatically. The function(s) below wrap around the native DOM `querySelectorAll` or jQuery and will automatically cache every object you lookup using them. This is actually better than caching your selectors in advance because the client only suffers the performance impact when that query actually gets done.Filed In: UncategorizedJanuary 30, 2014