John Jackson John Jackson - 1 month ago 8
jQuery Question

adding variable in jQuery selector?

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

$('.images').hover(function(){
var img = $(this).attr("title");
$(".image-border[title='img']").addClass('show');
}


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

Answer

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;
  }).addClass('show');
});