Snow Crash Snow Crash - 2 months ago 12
Javascript Question

Dynamic JavaScript variable

I'd like to be able to target an HTML element and I've got some PHP / JavaScript like this where

id = 1
:

echo 'var my_div_id = "div_" + id;
var my_div = $( "#my_div_id" );';

<div id="div_1">Div 1</div>


However, it doesn't seem to be working. i.e. I can't target the DIV. Note, when I was targeting it statically (i.e. using
$( "#div_1" )
it would work ok) so the problem is arising when I dynamically target it.

Is it something to do with
my_div_id
not being interpreted as I'm expecting?

Answer

try using $( '#' + my_div_id )

 echo "var my_div_id = "div_" + id;
       var my_div = $( '#' + my_div_id );";