34

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.

Community
  • 1
  • 1
montrealist
  • 5,593
  • 12
  • 46
  • 68

7 Answers7

49

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
  • 6,188
  • 1
  • 41
  • 63
14

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
  • 138,234
  • 66
  • 282
  • 345
9

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

Adam Luter
  • 2,193
  • 1
  • 15
  • 20
4

Use the array.join method to join them together

$(theArray.join(','));
Dan F
  • 11,958
  • 3
  • 48
  • 72
4

Going to officially answer your question: with a one-liner:

//If this is only one use variable you can use
$(['#p1','#p2','#p3','#p4','#p5'].join(',')).methodToUse();
//if you DO need it as a variable you can
var joined = ['#p1','#p2','#p3','#p4','#p5'].join(',');
$(joined).methodsToUse();

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, i => {
    $(peas[i]).click(() => {
        $(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 a function that removes the selected ID from the array and voila!

var peas = ['#p1','#p2','#p3','#p4','#p5'],
    poppy=(v,i)=>peas.toString().replace(`,${v[i]}`,'').replace(`${v[i]},`,'');

(// get each pea index
  $.each(peas,i=>///funciton(i){ code inside}

    (//set up each individual index's functions
      $('.peastock').append(`<p id="p${[i+1]}">I am ${peas[i]}</p>`),
      $(peas[i]).click(()=>(
        $(peas[i]).css({"color":"red","background-color":"rgba(128,0,0,0.1)"}),
        $(poppy(peas,i)).css({'color':'black','background-color':'rgba(255,255,255,0.2)'}))))),

  $('.peastock').append(`
    <div id="ree">ES6 isnt suitable for all of jQuery's usage!</div>
    <div>Since some functions inside of jQuery's methods dont require 'this' or 'return'</div>
    <div>You can learn this by going <a href="https://www.w3schools.com/Js/js_es6.asp">here</a></div>
  `),
  $("*").css({"margin":"0 auto","padding":"1%"}),
  $("* .peastock, .peastock, .peastock *").css({"background-color":"rgba(128,0,0,0.1)"})
);

I know someone is bound to want to know about each value array as jquery selectors. Hope everything goes well!

Source: jQuery .each() The fiddle in action (with updates!)

Gareth Compton
  • 159
  • 1
  • 12
3

I think you're looking for join.

var arr = ["#p1", "#p2", "#p3", "#p4", "#p5"];
$(arr.join(","))
Mark
  • 9,966
  • 7
  • 37
  • 39
0

Shorter:

$( ["#p1", "#p2", "#p3", "#p4", "#p5"].toString() );
Bnaya Zil
  • 89
  • 5
  • 1
    Many overcomplicated answers, while yours is (just a bit) faster. I'll edit it to fit the scope of jQuery. Nice one! –  Aug 25 '22 at 18:20