Take the 2-minute tour ×

If I have a varibale that changes on certain conditions how do I select it using Jquery selectors?

var id = 2
alert($('.'+id+ ' .title').val());
share|improve this question
Please clarify the question. What you have looks fine, aside from the fact that the variable is called "id" but you're using a class selector. –  Matt Ball Dec 1 '11 at 22:34
add comment

1 Answer

up vote 1 down vote accepted

your problem here is that you are starting a classname with a number. class names must start with an _ a - or a letter.

switch up your structure so its:

var id = 2
alert($('.' + 'title' + id).val());

or some variation so that id starts with an underscore, dash, or letter:

var id = 2
alert($('._' + id + ' .title').val());
share|improve this answer
The selector in your first example would be ..title2. –  James Montagne Dec 1 '11 at 22:53
whoops ill fix that –  Evan Dec 1 '11 at 22:53
add comment

Your Answer


