2

If my markup looks like this:

<div data-test="{ "value" : "bar", "_id" : 1234, "name" : "john", "age" : 25 }">...</div>
<div data-test="{ "value" : "foo", "_id" : 1235, "name" : "paul", "age" : 26 }">...</div>
<div data-test="{ "value" : "drummer", "_id" : 1236, "name" : "ringo", "age" : 22 }">...</div>

How would I select a particular element using JQuery if I only had the key 'bar' or 'foo'?

I could pull out the whole object for each row and iterate through it looking for a match but I'd rather not if there is a more efficient method.

How can I cleanly select based on the property of an object?

4
  • jQuery uses xpath for selecting object. Xpath has no support for embedded json structures. Commented Oct 18, 2012 at 8:48
  • But this: $('#myDiv').data('value') returns bar or foo so JQuery is able to operate on the object, no? Commented Oct 18, 2012 at 8:52
  • "returns bar or foo" ?? Not with this markup and code... Commented Oct 18, 2012 at 9:02
  • Can you use JSON syntax in your markup? Then you could use JSON.parse() and match the value element more cleanly. The difference is that you need to use double quotes rather than single quotes around the strings. Commented Oct 18, 2012 at 9:21

2 Answers 2

2

Try this

$('div[data-test$=": bar }"]')
$('div[data-test$=": foo }"]')

More details here

UPDATE: If attributes are not ending with bar/foo then you could try contains selector

$('div[data-test*="'value' : 'bar'"]')
$('div[data-test*="'value': 'foo'"]')

More details here

Or you could also use starts selector if it starts with value

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

2 Comments

I should have been clearer, the actual object is much more complicated and does not end with the value property. I'll update the question with a more accurate example.
If this solution works for you, then you are not interested in properties, but rather in attributes. That selector won't work for data properties set by, for example, .data("stuff", "things").
1

You can use:

$("div").filter(function() {
    return $(this).data("test").value == "bar";
})

jQuery.data() automatically parses a data value that's in JSON format into the corresponding object.

FIDDLE

3 Comments

.filter() is a more accurate solution as it will only return exact matches.
You need to change your outer quotes to single quotes or escape the inner double quotes.
You'd think so but actually Chrome renders the html like this (even when the template code is using single quotes) and, despite it looking wrong, I am able to successfully access the object using JQuery's .data() method. I admit, it's odd, but it's working.

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.