user826177
user826177

Reputation:

How to use a variable within a jQuery selector?

I'm trying to find an image with a 'src' that matches a variable. I have used 'alert' to make sure the variable 'currentThumbnail' is correct, so I think the problem is down to syntax. This is what I have at the moment:

var currentImage = $('.imageMain').attr('src');
var currentThumbnail = currentImage.substring(6);
var nextT = $('.thumbnails a img[src=currentThumbnail]');

The problem is with 'img[src=currentThumbnail]'. What do I need to change to make this valid?

I'd be happy to add any more information if it's unclear. Thank you!

Upvotes: 4

Views: 668

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

var nextT = $('.thumbnails a img[src=currentThumbnail]');

should be

var nextT = $('.thumbnails a img[src="'+ currentThumbnail +'"]');

You need String concatenation, because you're using variable currentThumbnail within a string.

An important commment from @ThiefMaster

The attribute values in selectors should be quoted. The docs says it's a requirement and I think the only reason why it's not enforced is backwards compatibility

Upvotes: 7

Related Questions