0

I am doing this but it's not working

html

<a href="#filter-year-y2013" data-filter-value=".y2013">2013</a>

jquery

var token = document.location.href.split('=')[1];
var attribu = "." + token;
$('a[data-filter-value= attribu]').css("background", "#ddd");

This question is different from this other question as I am not asking to target any selector with variable but a data attribute

Community
  • 1
  • 1
rob.m
  • 9,843
  • 19
  • 73
  • 162

1 Answers1

5

You need to concatenate the variable together with the string selector, try this:

$('a[data-filter-value="' + attribu + '"]').css("background", "#ddd");

Alternatively you could avoid the concatenation and use filter():

$('a').filter(function() {
    return $(this).data('filter-value') == attribu;
}).css("background", "#ddd");
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thanks man. Why is this question marked as a duplicate if it is not and also none of the answers on that question provides an answer to what I needed? e.g. none says about concatenation as your correct answer here did – rob.m Jan 28 '15 at 08:49
  • All of the other answers use concatenation - that's what the `$('#one img.' + id)` is in the top answer - where the `id` variable is joined with the string value. – Rory McCrossan Jan 28 '15 at 08:50
  • 1
    yes but I do know about that type of concatenation, it's a different way you need to do it in my case e.g. double quotes etc which I did not know and that question did not say it, however, i did found just now, unfortunatly, a correct helping answer on SO, maybe this question should be marked as a duplicate of this instead? http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value – rob.m Jan 28 '15 at 08:53
  • Isn't there an XSS vulnerability when passing the variable in this manner? – WPExplorer Jun 02 '20 at 03:02