Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

samiff
samiff
31,206 Points

jQuery Multiple Selectors

I'm working with some jQuery code examples, and I'm having a hard time understanding why

$(var1).add(var2).css("border", "thick solid red");

works for this page, but the following doesn't

$('var1, var2').css("border", "thick solid red");

Edit: I understand that in this example the newly created elements aren't part of the actual document until appended, but I guess I'm asking if the syntax exists to do it the way I was trying, or if you have to use add(), or just use two separate statements.

4 Answers

$('var1, var2'); will match elements with tagnames of 'var1' and 'var2', respectively.

However, $(var1, var2) may be what you're looking for, perhaps?

Without the quotes, it will interpret the selector contents as variables, not text to be interpreted.

samiff
samiff
31,206 Points

I tried using

$(orchidElems, lilyElems).css("border", "thick solid red");

in the example I posted, but that only matches the first of those variables, and not the second.

My Mistake :) I didn't check your example fully:

$.merge(orchidElems, lilyElems).css({border:"thick solid red"});

Should do it.

samiff
samiff
31,206 Points

Thanks Andrew. That technique does work. The syntax is still a bit weird to me though because you can select multiple page elements like $("div, .myClass"), but it doesn't work in this example for new variables (even without the quotes).

I ended up finding a a good Stack Overflow thread. Also for anyone who comes across this, the jQuery.merge() API (merge will alter your first array parameter!)