Reputation: 129
I'm trying to find element with jQuery
by its data attribute value. The problem is, that the value is object and find()
function doesn't work properly for me...
Data attribute value looks like this:
<tr class="odd" data-row="{"id_construction":2,"created_date":2015-11-30}">
And here is my script:
for(var i = 0; i < dataList.length; ++i){
var constructionId = dataList[i].id_construction;
if (constructionId == selectedConstructionId) {
$('.gridator').find('tr[data-row={id_construction:}').addClass('selected-construction');
}
}
value of dataList[i]
is {"id_construction":2,"created_date":2015-11-30}
How should I edit this script to find the wanted element? (Element which data-row
value is equal to dataList[i]
value)
Fiddle: https://jsfiddle.net/og1j1wc3/4/
Upvotes: 2
Views: 1930
Reputation: 34189
jQuery attribute selectors work with strings, not with objects stored as JSON.
You will have to iterate through every attribute value in order to find a necessary object:
var $greens = $("div").filter(function() {
return $(this).data("p").isGreen === true;
});
console.log($greens.length); // 3
$greens.css("color", "green");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-p='{"isGreen": true}'>
one
</div>
<div data-p='{"isGreen":true }'>
two
</div>
<div data-p='{"isGreen": false}'>
three
</div>
<div data-p='{ "otherAttribute": 42, "isGreen": true }'>
four
</div>
As you can see in this snippet, whitespaces and other attributes do not affect how this works because your work with it as with data, not as a string.
Note that according to documentation jQuery .data()
returns an object if data attribute contains JSON object:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
Upvotes: 2