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.
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.What you probably really want is
.filter():This way you use the (fast) CSS selector engine to get only relevant elements (those that have a
data-peopleattribute) and then filter the resultset using the callback function.