Is it possible to use multiple variables instead of selectors in jQuery
Just use the add
method:
$header_elements.add($footer_elements).css({color:'#ff0000'});
Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
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):
- Using $.merge() (average of 7ms)
- Using both variable one after the other (average of 10ms but the code needs to be duplicated)
- Using .add() (average of 16ms)
- Using selectors each time (average of 295ms)