cpcdev cpcdev - 1 year ago 49
Javascript Question

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

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download