Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use multiple variables instead of selectors in jQuery

Tags:

jquery

I know that it's faster to do the following:

var $header = $("#header"); $header.css({color:"#ff0000"}); $header.find("a").addClass("foo"); 

Instead of:

$("#header").css({color:"#ff0000"}); $("#header a").addClass("foo"); 

Because jQuery doesn't need to find the elements again in the DOM as we have direct reference to them.

Let's say that I have this:

var $header_elements = $("#header li"); var $footer_elements = $("#footer li"); 

And I use both individually for a few jQuery manipulations. But then, I need to do something on both. Using selector, I would do this:

$("#header li, #footer li").css({color:"#ff0000"}); 

But then, the DOM needs to be parsed again to find matching elements. Is there a way to use my previously declared variables instead of a new selector? Something like the following (which is not working, I know, it's to give an idea of what I'm looking for):

$($header_elements + $footer_elements).css({color:"#ff0000"}); 

I think that the selector returns some kind of array or object. What I'm looking for is a way to merge those. Anyone know if this is possible and how to do it?

Thanks for your help!

like image 741
Gabriel Avatar asked Aug 26 '10 15:08

Gabriel


People also ask

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

Can you use a variable in a jQuery selector?

Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.


1 Answers

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.

like image 63
djdd87 Avatar answered Oct 02 '22 14:10

djdd87