Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use jQuery( elementArray )?

Tags:

jquery

I set these up at the beginning of the script:

var grid = $('#grid');
var lines = $('#lines');
var background = $('#background');

Elsewhere in the script, I need to change the CSS for all 3 elements at the same time. Rather than doing this:

grid.css({...
lines.css({...
background.css({...

I want to do something like one of these:

$(grid, lines, background).css({...
$([grid, lines, background]).css({...

However, the only thing that seems to work is by referencing the IDs directly, like this:

$('#grid, #lines, #background').css({

I'd prefer to use references to the elements instead of the IDs directly, as they may change dynamically. Is this possible?

like image 572
velocityhead Avatar asked Oct 14 '11 19:10

velocityhead


2 Answers

Use .add():

grid.add(lines).add(background).css({...});

Demo: http://jsfiddle.net/mattball/xj5bb/

like image 66
Matt Ball Avatar answered Sep 23 '22 20:09

Matt Ball


It works with elements, not jQuery objects. You can use .add() method as said, or $([grid[0], lines[0], background[0]])

see this jsfiddle : http://jsfiddle.net/HqurT/1/

(source : http://forum.jquery.com/topic/jquery-elementarray-with-filled-elementarray )

I've maid a jsperf : http://jsperf.com/add-vs-elementarray

like image 29
nicolast Avatar answered Sep 22 '22 20:09

nicolast