0

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

That's it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.