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!

1 Answer 1

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";
}).
Sign up to request clarification or add additional context in comments.

2 Comments

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!
@Jasie Have a look at this question. It may explain some of this stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.