cpcdev
cpcdev

Reputation: 1222

Pass variable into jQuery attribute-contains selector

Is it possible to pass a variable into a jQuery attribute-contains selector?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
  id: vp-485858383,
  customTwo: "test"
}'>
asdf
</div>

$(function() {
    var testString = "vp-485858383";
  $('[data-vp*="id: ${testString}"]').css('color', 'red');
});

I have also tried:

$('[data-vp*="id:' +  testString + '"]').css('color', 'red');

JS Fiddle

Upvotes: 0

Views: 523

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you just need a space after id:

$(function() {
    var testString = "vp-485858383";
  $('[data-vp*="id: ' +  testString + '"]').css('color', 'red');
});

Demo

$(function() {
	var testString = "vp-485858383";
  $('[data-vp*="id: ' +  testString + '"]').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-vp='{
      id: vp-485858383,
      customTwo: "test"
}'>
asdf
</div>

Upvotes: 2

Related Questions