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.

0

7 Answers 7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

join() is exactly it. Thank you.
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();

Comments

9

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

Comments

4

Use the array.join method to join them together

$(theArray.join(','));

2 Comments

Hehe, I knew I'd be too slow on this darn iphone :-)
Thank you for taking the time anyway!
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!)

Comments

3

I think you're looking for join.

var arr = ["#p1", "#p2", "#p3", "#p4", "#p5"];
$(arr.join(","))

Comments

0

Shorter:

$( ["#p1", "#p2", "#p3", "#p4", "#p5"].toString() );

1 Comment

Many overcomplicated answers, while yours is (just a bit) faster. I'll edit it to fit the scope of jQuery. Nice one!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.