0

i'm messing around with arrays and have a very basic question. lets say i have this html-markup:

<div id="1" style="width: 50px; height: 50px; background-color: #ff0; display: none;"></div>
<div id="2" style="width: 50px; height: 50px; background-color: #ffc; display: none;"></div>
<div id="3" style="width: 50px; height: 50px; background-color: #fcc; display: none;"></div>

and create the following array:

var testArr = ['$("#1")', '$("#2")', '$("#3")'];

why i cant execute the following function to work:

 function showArr() { testArr[2].show(); 
  };
 showArr();

therefore shouldn't #3 get displayed?

thanks

3
  • This generally isn't the way to do this. You select all the elements like var elems = $('#1, #2, #3') and then based on the order in the DOM you select what to show, like elems.eq(2).show(), you don't stick elements in an array unless you have a really good reason to do so, and this doesn't look like it is such a reason. And you shouldn't use just a number for ID's. Commented Jun 11, 2013 at 22:41
  • yea, but i only made that for understanding arrays. its not like i want to store selector into arrays. its just that i was trying out, and understand how they work! Commented Jun 11, 2013 at 22:46
  • If you stored just the ids in the array, you could use the (fairly-horrible) approach here: (horrible) demo (don't seriously consider using this). Commented Jun 11, 2013 at 22:55

2 Answers 2

3

No. This won't work because you're attempting to run a function on a string.

testArr[2] is '$("#3")'. Not a jQuery object: it is a string that contains code. So testArr[2].show() means '$("#3")'.show(). Since strings don't have a show method, this won't work.

You need to store jQuery objects, not strings:

var testArr = [$("#1"), $("#2"), $("#3")];
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for explanation, i'm learning and people like you help me alot! works fine!
or you can store selectors in array - var testArr = ["#1", "#2", "#3"]; and then use in jQuery object - $(testArr[2]).show();
1

First off, ids can't start with numbers. Secondly, dont store it as a string, just store the object.

testArr = [ $('#item-1'), $('#item-2') ];

4 Comments

Under HTML5 they can (but they're an absolute nuisance to select in CSS if they do...).
why shouldn't i use numbers as id? Worked always fine for me!
@supersize: try using CSS to style #1, and then tell me it works 'fine.'
works pretty good! just kidding, you got me, thanks for the hint... ive never realised this!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.