John Jackson John Jackson - 2 months ago 14
jQuery Question

adding variable in jQuery selector?

Im attempting to select an element via its title, which is stored in a variable:

var img = $(this).attr("title");

however as you can imagine, the variable is being treated as part of the string... is this even a possibility?


You're probably going to get answers telling you to use string concatenation, such as:

Don't do it this way
$('.images').hover(function () {
  var img = $(this).attr('title');
  $('.image-border[title="' + img + '"]').addClass('show');

This is a bad idea. You haven't escaped the value stored in img, and it could break the selector.

The right way to do this sort of check is to select everything you can statically, and then filter the results to only include the ones that match the dynamic value:

Do it this way
$('.images').hover(function () {
  var img = $(this).attr('title');
  $('.image-border').filter(function () {
    return $(this).attr('title') === img;