Reputation: 31033
I need to attach an alphanumeric string to a set of nodes; each node has a string (which is not unique).
Then I need a click handler that filters by that string's value. I see jQuery's .data() function will store the strings on the nodes, but then I can't select on them. Am I supposed to create the nodes using the attr
property like this:
var node = $('<div class="node"></div>').attr('data-string', "18nn4v");
And then filter like this?
$('#something').click(function() {
$('.node[data-string="18nn4v"]')...//whatever
});
It would be nice if I could just use .data()
. It just seems a little lopsided since jQuery automatically imports all "data-XXX"
attributes into that element's property: .data(XXX)
, but it does not export all .data(XXX)
properties to "data-XXX"
attributes!
Upvotes: 1
Views: 168
Reputation: 238115
The jQuery attribute selector works only on genuine attributes -- i.e. what has been defined in the original HTML or by setAttribute
(used by jQuery's attr
). This is by design and is correct behaviour.
If you want to use data
, you'll have to do the filtering manually with filter
:
$('.node').filter(function() {
return $.data(this, 'string') === "18nn4v";
}).
Upvotes: 2