tony gil
tony gil

Reputation: 9554

Finding element(s) by data attribute = variable using jQuery

Using (custom) jQuery data-attributes to retrieve the elements where these icons are displayed, I am successfully changing icons with this working code:

<i class="glyphicon glyphicon-check" data-year="2014" data-flag_check="1"></i>
...
<script>
   ...
   $('i[data-year="2014"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

But, if I attempt to replace the constant 2014 with a variable, my code stops working.

var yearIn = "2014";
$('i[data-year=yearIn]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

Is it possible to perform this operation with a variable?

If so, what is wrong in my syntax?

Upvotes: 1

Views: 2283

Answers (2)

Dij
Dij

Reputation: 9808

You are using the string literal 'yearIn' rather than the variable yearIn. Do something like this to concatenate the strings:

$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073969

You're just missing string concatenation:

var yearIn = "2014";
$('i[data-year=' + yearIn + ']').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^^^^^^^^^^^^^^

Or in ES2015+ you could use a template literal with a substitution token:

  var yearIn = "2014";
  $(`i[data-year=${yearIn}]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
//  ^------------^^^^^^^^^-^

FWIW, I always use quotes around the value in the selector when it comes from a variable, just in case the variable ends up with something in it with spaces, etc.:

var yearIn = "2014";
$('i[data-year="' + yearIn + '"]').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^--------------^

or

var yearIn = "2014";
$(`i[data-year="${yearIn}"]`).removeClass('glyphicon-check').addClass('glyphicon-unchecked');
// ------------^---------^

Upvotes: 5

Related Questions