1

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!

atp
  • 30,132
  • 47
  • 125
  • 187

1 Answers1

2

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";
}).
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • I see. I guess 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! – atp Jun 08 '11 at 22:31
  • @Jasie Have a look at [this question](http://stackoverflow.com/questions/5874652/prop-vs-attr/5884994#5884994). It may explain some of this stuff. – lonesomeday Jun 08 '11 at 22:37