Adam Ritenauer
Adam Ritenauer

Reputation: 3181

JQuery Find with string variables

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

i.e.

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

Upvotes: 2

Views: 451

Answers (4)

Russ Cam
Russ Cam

Reputation: 125518

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

Upvotes: 0

Steerpike
Steerpike

Reputation: 17554

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).

Upvotes: 5

KyleFarris
KyleFarris

Reputation: 17548

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();

Upvotes: 0

JaredPar
JaredPar

Reputation: 755141

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

Upvotes: 3

Related Questions