Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!)