With JQuery, it is bad practice to call a selector multiple times like this:
$('#myDiv').addClass('class1');
$('#myDiv').removeClass('class2');
$('#myDiv').append(`<div>Hello World`);
So it often advised to cache the selector as such:
let element = $('#myDiv');
element.addClass('class1');
element.removeClass('class2');
element.append(`<div>Hello World`);
But lets say for example this is done:
let element = document.getElementByID('myDiv');
$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);
OR
let element = $('#myDiv');
$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);
Does either or both of those have the same negative impact when calling the selector that way?
2
Answers
No, they dont have the same negative impact. You have already reference to the DOM element and there is no need to traverse DOM tree again to look for it. Both cases add some overhead and are unnecessary.
In general use chaininng where possible and keep jquery object reference if you need it frequently.
UPDATE
I wasnt right about jQuery object creation. jQuery always do some "heavy" work.
Results for one million loop on my PC:
Using jsbench to test.
29019 ops/s
30490 ops/s
28132 ops/s
31404 ops/s
Last one was the fastest. I am guessing because we already have a jquery reference which was then passed further. I am surprised it beat the second test case, maybe just my browser doing something. I would put the 2nd and last to be equivalent in speed.