2

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

i.e.

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

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was missing... Thanks
3

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

2 Comments

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.