0

How would you use an array index as a jquery selector?

for example if I have:

 array[0] = someId;
 array[1] = someId;

 for(var i; i<array.length; i++){
     $("#"+array[i]").find(.....)
 }

I would like to be able to use the value stored in the array index as my id for the selector.

thanks

5
  • 2
    jquery selectors are just strings. Commented Mar 15, 2012 at 22:18
  • 2
    $("#"+array[i]). Remove the extra " after [i]. Commented Mar 15, 2012 at 22:18
  • 1
    what does not work with your code (except the one quotation mark to much)? Commented Mar 15, 2012 at 22:18
  • $("#"+array[i]).find("#someELement"); - You had a stray closing " in your string, no need for it. Commented Mar 15, 2012 at 22:18
  • Closing and down-voting because this is a syntax error. Learn your tools. Commented Mar 15, 2012 at 22:47

5 Answers 5

2

Your code works fine, except for the extra ".
jQuery selectors are ordinary strings.

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

Comments

2

Remove the last quote in selector array[i] will be a string and all you are doing is concatenating a string to create the selector

$("#"+array[i] ).find(.....)

Comments

1

Don't forget to set i to 0:

 array[0] = someId;
 array[1] = someId;

 for(var i=0; i<array.length; i++){
     $("#"+array[i]).find(.....)
 }

Comments

1

You can create a multiple selector by joining the indexes of your array:

$('#' + array.join(', #')).find(.....)

This way you don't loop through anything, you let jQuery deal with the fact that you're doing something to multiple elements.

Here is a demo: http://jsfiddle.net/y7UQ9/

Docs for multiple selectors: http://api.jquery.com/multiple-selector/

Comments

0

You've got a syntax error to start with:

$("#" + array[i]).find(.....)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.