views:

836

answers:

6

I have an array of strings that are valid jQuery selectors (i.e. IDs of elements on the page):

["#p1", "#p2", "#p3", "#p4", "#p5"]

I want to select elements with those IDs into a jQuery array. This is probably elementary, but I can't find anything online. I could have a for-loop which creates a string "#p1,#p2,#p3,#p4,#p5" which could then be passed to jQuery as a single selector, but isn't there another way? Isn't there a way to pass an array of strings as a selector?

EDIT: Actually, there is an answer out there already.

+7  A: 

Well, there's 'join':

["#p1", "#p2", "#p3", "#p4", "#p5"].join(", ")

EDIT - Extra info:

It is possible to select an array of elements, problem is here you don't have the elements yet, just the selector strings. Any way you slice it you're gonna have to execute a search like .getElementById or use an actual jQuery select.

Paul
join() is exactly it. Thank you.
dalbaeb
+6  A: 

Try the Array.join method:

var a = ["#p1", "#p2", "#p3", "#p4", "#p5"];
var s = a.join(", ");
//s should now be "#p1, #p2, #p3, ..."
$(s).whateverYouWant();
matt b
A: 

Use the array.join method to join them together

$(theArray.join(','));
Dan F
Hehe, I knew I'd be too slow on this darn iphone :-)
Dan F
Thank you for taking the time anyway!
dalbaeb
A: 

I think you're looking for join.

var arr = ["#p1", "#p2", "#p3", "#p4", "#p5"];
$(arr.join(","))
Mark
+2  A: 

What about $(foo.join(", "))?

Adam Luter
A: 

I like to write something like that:

$jq = jQuery.noConflict();
$jq('#uk, #ru').click(setLang).hover(changeImageOver, changeImageOut);
Ruslan