jquery .each produces 'undefined' whenever .data is used on the elements returned

891 views Asked by At

I'm trying to process all select elements with a specific data- attribute set.

I've got the loop working to pick up the element, but whenever I try to find the value of its other data- attributes I get undefined error messages.

Here is the loop:

$('select[data-hm-observed="1"]').each(function(idx, sel) {
        alert(sel.getAttribute('data-hm-url'));
        alert(sel.data('hmUrl'));
});

In the loop the first alert works, but the second produces:

TypeError: 'undefined' is not a function (evaluating 'sel.data('hmUrl')')

If I use the Safari console I can get the select object, put it in a variable, and interrogate its data- attributes without issue.

It seems that the .each() is having an effect on the sel variable contents - but I can't understand what.

Using JQuery 1.7.1

UPDATE:

Just discovered that if I change the loop so that it explicitly gets the element again, it all works:

$('select[data-hm-observed="1"]').each(function(idx, sel) {
            xx = $(sel);
        alert(sel.getAttribute('data-hm-url'));
        alert(xx.data('hmUrl'));
});

Is this the correct solution? Can I infer from this that the element passed into the loop by .each hasn't been 'processed' by jquery, and that I have to pull it myself via $(...) so that jquery does its stuff to it - this doesn't feel right - but its working.

1

There are 1 answers

2
kapa On BEST ANSWER

sel is a DOM Object here, not equipped with the abilities of a jQuery Object. First, you should turn this DOM Object into a jQuery Object like this:

alert( $(sel).data('hmUrl') );

Alternatively, you can also use $(this).data('hmUrl'), because this will refer to sel (the current DOM element in the iteration).