Reputation: 3181
Can I query the DOM with $() using a string variable as a parameter?
i.e.
var divContainerID = "divBlock1";
$(divContainerID).show();
Upvotes: 2
Views: 451
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
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
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
Reputation: 755141
Yes. As long as the string represents a valid query, this should present no problem.
Upvotes: 3