Thursday, 8 August 2013

Can this (potential bug?) in jQuery be worked around?

Can this (potential bug?) in jQuery be worked around?

I want to use a .filter function against a large number of elements where
I'm checking for a data-* attribute.
The problem is that the jQuery selector seems to use the original value.
If I set a data value using $('whatever').data('key', newValue) and then
try to use a selector $('[data-key=newValue]') then nothing is found.
Here's my test HTML:
<div id="test" data-dummy="foo"></div>
<div id="result"</div>
Then:
$('#test').data('dummy', 'bar');
$('#result').
append('<div>Where dummy=foo: ' + $('[data-dummy="foo"]').length +
'</div>').
append('<div>Where dummy=bar: ' + $('[data-dummy="bar"]').length +
'</div>');
Outputs:
Where dummy=foo :1
Where dummy=bar :0
It looks like, for the selector engine, only the original value is used in
selectors.
To work around this I'm using a .filter, but as this filter will run for
large numbers of elements I don't want to create a new jQuery object for
each match. For this sort of circumstance jQuery provides some global
functions.
Basically I should be able to use $.data(element, instead of
$(element).data(, but this doesn't work either: $.data(element, returns
undefined.
However that appears to only be before a jQuery object is initialised:
var domEle = document.getElementById('test');
var globalBefore = $.data(domEle, 'dummy');
var first = $(domEle).data('dummy');
var globalAfter = $.data(domEle, 'dummy');
$('#result').
append('<div>$.data before: ' + globalBefore + '</div>').
append('<div>new $(): ' + first + '</div>').
append('<div>$.data after: ' + globalAfter + '</div>');
Outputs:
$.data before: undefined
new $(): foo
$.data after: foo
Weird. Never mind, the question is can I work around it? Is there any way
to initialise whatever's happening for a new $ object without creating one
for every tested node?
JS Fiddle demo: http://jsfiddle.net/kU4th/

No comments:

Post a Comment