1

I have the following data attribute object:

<div data-vp="{
      id: "vp-485858383",
      customTwo: "test"
}">
</div>

I'm trying to target data-vp with the specific id value in jQuery:

$(['data-vp with id:vp-485858383'].parent().find('.fa.fa-times').show();

I'm doing this so I can show only a specific instance of .fa.fa-times rather than all elements with the .fa.fa-times class.

I know the selector above won't work obviously, but is it possible to target both data-vp along with the specific ID?

3
  • So the data-vp is an object? Commented May 23, 2017 at 0:09
  • Yes I turned it into an object Commented May 23, 2017 at 0:09
  • If you are able to split it into <div id="something" data-vp="something else"> it would be an easy selector. Do you have that kind of control? Or you could do a wild card selector. Commented May 23, 2017 at 0:13

1 Answer 1

5

You can use the attribute-contains selector for that:

$(function() {
  $('[data-vp*="id: vp-485858383"]').css('color', 'red');
});
<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>

Note that your text must be exactly the same.

Another option is to filter the elements based on the data-vp attribute:

$(function() {
  $('[data-vp]').filter(function(i, el) {
    return $(el).data('vp').id == 'vp-485858383';
  }).css('color', 'red');
});
<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>
<div data-vp='{
      "id": "vp-123",
      "customTwo": "test"
}'>
asdf
</div>

For that you must have the content of the data-vp attribute to be a valid json string.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.