I know that it\'s faster to do the following:
var $header = $(\"#header\");
$header.css({color:\"#ff0000\"});
$header.find(\"a\").addClass(\"foo\");
<
You can use add or merge method:
Add
$header_elements.add($footer_elements).css({color:'#f00'});
merge
$.merge($header_elements, $footer_elements).css({color:"#f00"});
Both work, but add is more performant.
Source: http://jsperf.com/add-vs-merge
Credit: I upvoted @GenericTypeTea and @Gabriel answers, did a summary of both, compared them and here is the result.
Pass an array of references:
$([$header_elements, $footer_elements]).css({color:"#ff0000"});
You could always set all of the elements to one variable:
var $lis = $('#header li, #footer li');
$($lis).css({color:"#ff0000"});
It does not matter performance wise wether you'll do something like (even if it worked):
$($header_elements + $footer_elements).css({color:"#ff0000"});
or do them separately:
$($header_elements).css({color:"#ff0000"});
$($footer_elements).css({color:"#ff0000"});
as jquery will internally go through the supplied arguments using each()
.
If the principle is more DRY
inspired, than performance wise, you can create a function:
function makeThemRed( el ) {el.css({color:"#ff0000"})}
and then
makeThemRed($header_elements);
makeThemRed($footer_elements);
or even:
function makeThemRed()
{
var l=arguments.length,
o=0;
while (o<l) {
arguments[o++].css({color:"#ff0000"})
}
}
and then
makeThemRed($header_elements, $footer_elements); //any number of parameters
I found the solutions a few minutes after posting this. For those who are wondering, here it is:
$.merge($header_elements, $footer_elements).css({color:"#ff0000"});
Is it faster? I don't know yet, I'll need to run some tests to find out.
EDIT:
I tested it with JS Fiddle here : http://jsfiddle.net/bgLfz/1/
I tested using selector each time, variable for both selector, variables with $.merge() and using .add(). Each test was run 1000 times.
Results on my side are as follow (from faster to slower):
The thing with using 'merge' is that it's limited to just two selectors, and using 'add' will be so messy if it's more than two, so if it's more than two, you should use 'each' like this:
$([selector1, selector2, selector3, .....etc]).each(function(){
// your code here
});