0

I need to fetch one of json encoded data inside data-people:

<ul>
  <li data-test="one" data-people='{"name" : "Paul", "color" : "black"}'>Paul</li>
  <li data-test="two" data-people='{"name" : "John", "color" : "blond"}'>John</li>
  <li data-test="three" data-people='{"name" : "Jane", "color" : "black"}'>Jane</li>
</ul>

It is pretty straight forward to fetch via data-test (just example):

$('ul li[data-test="two"]').show();

Now I want to show ul li with data-people that has color blond (ignoring data-test that only exist for sample above).

I tested below but this doesn't work as expected:

$('ul li[data-people="{"color": "blond"}"]').show();

I don't mean to get color value like: $('ul li').data('people').color, but to do proper CSS syntax inside the object.

Any hint is very much appreciated. Thanks.

1 Answer 1

5

You can't do this in any clean way using just selectors except by using the *= ("attribute contains") selector. And that one will only work if the JSON contains exactly that substring - remove the space before : and it will stop working.

$('ul li[data-people*=\'"color" : "blond"\']').show();

What you probably really want is .filter():

$('ul li[data-people]').filter(function() {
    return $(this).data('people').color == 'blond';
}).show();

This way you use the (fast) CSS selector engine to get only relevant elements (those that have a data-people attribute) and then filter the resultset using the callback function.

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

6 Comments

Hmmm, sounds reasonable. Is this definitive? So I can mark yours as a reply. Thanks
Notice this is not CSS syntax, these are jQuery selector syntaxes
And the question is tagged with jquery ;)
I'm talking about the title ;)
Actually the first example works with just CSS, too: jsfiddle.net/ThiefMaster/7f3HK
|

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.