Nathan Nathan - 9 months ago 52
jQuery Question

Variables inside of selectors

I saw a bunch of other threads that ask how you can combine variables with jQuery selectors, things like

$('.middle', $top)
to get whatever
is if it's inside of

What I'm looking for is how to combine them like this:

var gallerymodal_number = $(this).attr('data-gallerynumber');

So say that
ends up being a value of 2.

My code works if I just literally write out:

var galleryitem = '*[data-galleryitem="2"]';

But I need to get it via the variable above.

So my question is how do I do something like this:

var galleryitem = $('*[data-galleryitem="' + gallerymodal_number + '"]');

I just get an object returned with that particular code.

var galleryitem = '*[data-galleryitem="' + gallerymodal_number + '"]';

All you are doing here is creating a string with the value *[data-galleryitem="2"]

To return an object you need to use your string as a jQuery selector:

var galleryitem = $('*[data-galleryitem="' + gallerymodal_number + '"]');

Or to make what you are currently doing a little clearer:

var selectorString = '*[data-galleryitem="' + gallerymodal_number + '"]';
var galleryitem = $(selectorString);