I want to understand the best way to improve the performance of jQuery code.
Actually, I know how to cache the jQuery selectors to not touch the DOM multiple times as follow:
The worst way
$('.selector').text('Text'); $('.selector').text('New Text');
The better way
var elem = document.querySelectorAll('.selector'); $(elem).text('Text'); $(elem).text('New Text');
The best way
var $elem = $('.selector'); $elem.text('Text'); $elem.text('New Text');
First Question: Why the third method is faster than the second, and what actually
$(elem) do here?
Second Question: When I use