Reputation: 265
Is it possible to set some data by using the jQuery data method and then later query it? Something like ... find all elements with data foo == true?
Upvotes: 12
Views: 8114
Reputation: 141859
Not possible with just the data
API without looping through each element in the DOM, and checking to see if it contains that data item with the specified value.
If the data is simple, perhaps you can use HTML5 data attributes which are also searchable through selectors.
$("selector").attr("data-key", "theKey");
Later select all objects that have an attribute named "data-key"
with the value true
using
$('[data-key="true"]')
Upvotes: 5
Reputation: 630339
You can use .filter()
to select the elements you want, like this:
$("someSelector").filter(function() { return $.data(this, "foo"); });
In this case since you're checking a boolean it's very simple, for checking against a value just add the comparison, like this:
$("someSelector").filter(function() { return $.data(this, "foo") == "value"; });
Upvotes: 26