views:

93

answers:

3

so I have a div of class 'example'

in javascript i have: var selectWithThis = 'example'

Using this variable how would I write a $() selector to select this div?

A: 

$('.' + selectWithThis);

To use what ever class/string is stored in the variable.

Shaun Humphries
+4  A: 
var elements = $('.' + selectWithThis);

Note that it returns an array of all elements with the same class. If there is only one element, still an array with just an element.

Chetan Sastry
A: 

If you are sure there's just one DIV or care for the first one only, do as Chetan pointed out, but use either an indexer or a better selector:

Get the first element (returns a DOM object):

var element = $('.' + selectWithThis)[0]

Get the first element (returns a jQuery object):

var element = $('.' + selectWithThis).eq(0)

Get the first element (returns a jQuery object):

var element = $('.' + selectWithThis + ':first')

To further get the underlying DOM object you can always append [0] to the query.

Pawel Krakowiak