Search code examples
jqueryrel

Find and add/remove class from link with matching rel value


Almost solved this, but it seems I'm not allowed to match with variables inside the jQuery "a[]" tag. I'm trying to connect an interactive map with a list of links that show active/inactive states when the user clicks on the corresponding area on the map -

// Inside a click event with var active containing the fetch from the map

var active = "Lorem ipsum";

if($('a[rel^=' + active + ']', '.regions')) {
  if ($('a[rel^=' + active + ']', '.regions').hasClass('active')) {
    $('a[rel^=' + active + ']', '.regions').removeClass('active');
   }
   else {
     $('a[rel^=' + active + ']', '.regions').addClass('active');
   }
}

Solution

  • This may be what you're looking for. I'm assuming you have some class of the links you want to toggle, so you should probably add that to the selector so you're not selecting all links, but this removes the active class from everything and then adds it back to only those with the rel attribute being what you've grabbed from the map.

    var active = 'something';
    $('a').removeClass('active').filter('a[rel^="'+active+'"]').addClass('active');