Reputation: 35223
Example:
<div data-object="{ 'foo' : 123 }"></div>
<div data-object="{ 'foo' : 456 }"></div>
What would be the fastest way to find the div with foo value 123? At the moment im looping through the divs, converting the stringified object to a js object and check if the foo value is equal to 123? Can this be done without a loop? Thanks
Upvotes: 0
Views: 166
Reputation: 324
Use jquery selector
function getdiv(id) {
var divs = $('div[data-bh="{"foo":' + id + '}"]');
}
Upvotes: 1
Reputation: 2961
You dont need to parseJson, this should work
var divs = $("div").filter(function() {return $(this).data("object").foo == 123;});
read towards the end to see more examples, http://www.elijahmanor.com/2012/03/find-jquery-bug-5-defective-data.html
but as @Rory Mentioned, this does use loop internally
Upvotes: 0
Reputation: 337714
You could use filter()
var divs = $("div").filter(function() {
var data = $.parseJSON($(this).data("object"));
return data.foo == 123;
});
This does still use a loop internally though.
Upvotes: 2