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.
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.
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();
What about $(foo.join(", "))
?
Use the array.join method to join them together
$(theArray.join(','));
I think you're looking for join.
var arr = ["#p1", "#p2", "#p3", "#p4", "#p5"];
$(arr.join(","))
If you want them to do something individually there is also .each();
In the example below, each p ids clicks makes any one of them red:
var peas = ['#p1','#p2','#p3','#p4','#p5'];
$.each(peas, function(i){
$(peas[i]).click( function(){
$(peas[i]).css({'color':'red'});
});
});
When you throw 'i' into a function parameter, it finds the values inside the arrays appropriately. When you do '.each()' the format looks like this:
$.each(array, function(i){
// any code you wish as long as you have an array selector
//$(array[i]).whatever function
});
An even bigger example. Say you want to make the P you click on red, but want the other ps return to default color. Just make an array of nonPea and voila!
var peas = ['#p1','#p2','#p3','#p4','#p5']
, nonPeas = ['#p5, #p2, #p3, #p4'
,'#p1, #p5, #p3, #p4'
,'#p1, #p2, #p5, #p4'
,'#p1, #p2, #p3, #p5'
,'#p1, #p2, #p3, #p4']
;
$.each(peas, function(i){
$(peas[i]).click( function(){
$(peas[i]).css({'color':'red'});
$(nonPeas[i]).css({'color':'black'});
});
});
I know someone is bound to want to know about each value array as jquery selectors. Hope everything goes well!
Source: jQuery .each()
Shorter:
["#p1", "#p2", "#p3", "#p4", "#p5"].toArray()