Question

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

i.e.

var divContainerID = "divBlock1"; 
$(divContainerID).show();
Was it helpful?

Solution

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

OTHER TIPS

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top