0

I want to check whether an element with the name "shape_7" is visible. When I perform the following JavaScript it works fine:

var element = shape_7;

if( $(element).is(':visible') )
{
//my code
}

However, if I perform the following JavaScript it doesn't work:

var counter = 7;
var element = 'shape_' + counter;

if( $(element).is(':visible') )
{
//my code
}

Unfortunately, I need the second case (number as variable) in my situation. How has the second code to be corrected in order to work properly?

Thank you very much in advance for any help!

Pointy
  • 405,095
  • 59
  • 585
  • 614
Tall83
  • 343
  • 1
  • 4
  • 8
  • Your jQuery calls are looking for `` in the DOM. If you want to find an element with the **id** "shape_7", you want `"#shape_7"`. Otherwise your two pieces of code will do exactly the same thing. – Pointy Feb 09 '17 at 00:46
  • 2
    It appears that `shape_7` is another variable. Where is that coming from? You're defining element as equal to another variable in the first, whereas it's an element selector string in the second. The second is looking for a `` element in your page. – forrestmid Feb 09 '17 at 00:46
  • 1
    post your code in https://jsfiddle.net so we can reproduce it. – Yaron Yosef Feb 09 '17 at 00:51
  • I had this problem when using a JavaScript API, so it was quite a special situation. However the answer of Philip works perfectly fine! – Tall83 Feb 09 '17 at 01:01

2 Answers2

1

You can access your shape_* variables on the window object if it is defined globally, so you could do something like window['shape_' + counter].

Again you can... But you really shouldn't be coding like that. Instead you should try creating an array with the values: var shapes = ['#first', '#second', '#third'];

Then you can access the values by index: $(shapes[0]);

REMEMBER

Setting properties on the window objects makes them global, which means all code can get and set these property values. It is therefore considering bad practice, and you should try to avoid it. Look into IIFE's

Community
  • 1
  • 1
Phillip
  • 6,033
  • 3
  • 24
  • 34
0
var counter = 7; 
var element = 'shape_' + counter;
if( $('#'+ element).is(':visible')){//my code}

//or you can use .length if it is visible in the DOM
if( $('#'+ element).length){//my code }