4

http://jsfiddle.net/mblase75/NfzbA/ -- using jQuery 1.9.1

var $opts = $('.plant-page').map(function (i, el) {
    return $('<option>');
}).appendTo('#change-page select');

The error in the JavaScript console says: Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

When I switch to jQuery 1.8.3, result is as expected -- the option elements are appended to the select: http://jsfiddle.net/mblase75/NfzbA/2/

Am I doing something wrong?

1 Answer 1

3

In jQuery 1.9.1, if I rewrite the .map() callback function to return a DOMelement instead of a jQuery object, it works as expected: http://jsfiddle.net/mblase75/NfzbA/3/

var $opts = $('.plant-page').map(function (i, el) {
    return $('<option>').text(this.id)[0];
}).appendTo('#change-page select');

When I submitted this as a jQuery bug (http://bugs.jquery.com/ticket/13567), I was told:

Resolution set to notabug

You are trying to append a jQuery object that is inside a jQuery object, since you inserted a jQuery object into said jQuery object via the $.fn.map(). This is not supported, but obvious enough. We generally don't make a list of everything that cannot be in a jQuery set because there is an infinite list of possibilities for doing it wrong. Your rewrite looks better.

So: even though this worked in jQuery 1.8, it's considered a reversion to expected behavior rather than a bug. .map() callbacks should always return DOMelements instead of jQuery objects.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree with the assessment in the bug report. All jQuery iteration methods work this way. Inside the callback method, this is a DOM Node, not a jQuery object, the returned value should be in that same form. $([$(),$(),$()]) also no longer works even though it used to in the past.
@KevinB I agree, too -- but then again, $($some-jQuery-object) still returns a valid jQuery object!

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.