Snow Crash Snow Crash - 11 months ago 61
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
not being interpreted as I'm expecting?

Answer Source

try using $( '#' + my_div_id )

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