views:

262

answers:

4

Can I query the DOM with $() using a string variable as a parameter?

i.e.

var divContainerID = "divBlock1"; 
$(divContainerID).show();
+3  A: 

Yes. As long as the string represents a valid query, this should present no problem.

JaredPar
I love this site... Thanks I needed a sanity check on that one.
Antilogic
@Antilogic, this site is addictive. Be careful how much time you spend here or you may become stuck like the rest of is :)
JaredPar
A: 

Of course man, sometimes this is the only way. But, just so you know, the query you have in your example isn't a valid query. Presumably you are querying a class or id...

It would need to be like this:

var divContainerID = "#divBlock1"; 
$(divContainerID).show();

or:

var divContainerID = ".divBlock1"; 
$(divContainerID).show();
KyleFarris
+5  A: 

It should be:

var divContainerID = "divBlock1"; 
$('#'+divContainerID).show();

if divContainerID is an actual id of an element or

var divContainerID = "divBlock1"; 
$('.'+divContainerID).show();

if it's a class (which I'm kind of assuming it isn't, but I thought I'd give it to you anyway).

Steerpike
That's what I was missing... Thanks
Antilogic
A: 

Yes, but remember the string will need a

  • # prefix if it is an id

  • . prefix if it is a CSS class

Otherwise, it's assumed to be a HTML element

Russ Cam