Jquery Selector Re-use Best Practice
When storing a DOM object as a variable, which is the best practice use of that variable: It seems like I have seen it both ways, and as you can see, they both do the job. Options
Solution 1:
The second option is completely valid and good practice, however the first makes no sense. You're trying to jQueryify an object which has already been jQueryified. It basically is something like $($("body"))
.
Also note that it's good practice to prepend $
to variables which contains jQuery object. Your code should look like this:
var$myElement2 = $(".container").find('ul li:eq(2)');
$myElement2.css('background', 'blue');
As @Terry wrote, the most optimized way would be:
var $c = $(".container ul li");
var $second = $c.eq(2);
Solution 2:
You are right, the first case is redundant, and actually takes longer to execute (albeit not by a whole lot)
You can see this in the snippet here:
var s = window.performance.now();
var myElement1 = $(".container").find('ul li:eq(1)');
$(myElement1).css('background', 'red');
var e = window.performance.now();
console.log(e - s);
s = window.performance.now();
var myElement2 = $(".container").find('ul li:eq(2)');
myElement2.css('background', 'blue');
e = window.performance.now();
console.log(e - s);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="container"><ul><li>One</li><li>Two</li><li>Three</li></ul></div>
It's giving me about a 2 to 3 millisecond difference in speed.
I'd stick with the second option as it's cleaner and faster.
Post a Comment for "Jquery Selector Re-use Best Practice"