简体   繁体   中英

Why $(document).append() doesn't work in jQuery 1.9.1?

Why following piece of code doesn't work since jQuery 1.9.1? With previous versions works fine.

$(function () { 
    $(document).append(test);
    document.write('done');
});
var test = {
    version: "1.0",
};

JSFiddle: http://jsfiddle.net/Chessjan/NsjqM/

In JS console it issues error like this:

TypeError: document is null
safeFrag = document.createDocumentFragment(); jquery-1.9.1.js (line 5823)

Edit:

Thanks everybody for quick and extensive aswers. Observed issue was found by accident, and of course, $(document.body).append() is proper approach.

jQuery 1.9.x calls

this[ 0 ].ownerDocument

within its buildFragment() method. Since you pass in the document , the call

document.ownerDocument

will reference to null and cause the error. Any other node will reference the document , which of course, works.


Conclusion: Don't call $(document).append() but use $(document.body) for instance.

Your code will of never worked. It has to document.body not document .

Here's a few examples in different versions of it not working:

jQuery 1.6.4: http://jsfiddle.net/us9Kz/
jQuery 1.7.2: http://jsfiddle.net/us9Kz/1/
jQuery 1.8.3: http://jsfiddle.net/us9Kz/3/
jQuery 1.9.1: http://jsfiddle.net/us9Kz/4/
jQuery 2.0.0b1: http://jsfiddle.net/us9Kz/5/

Code working with document.body (on jQuery 1.9.1): http://jsfiddle.net/us9Kz/6/

To answer your question i tried in JSfiddle all the available jQuery versions. It happened to give the same error.

Why it doesnt work: document becomes something like [object HTMLDocument] when cast to string, and there is of course no such id, it will return null.

The following works:

var test = "1.0"
$('body').append(test);

or doing it trough object notation like you did:

var test = {
    version: '1.0'
}
$('body').append(test.version)

Inside the jQuery code it has this line:

jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );

this is the jQuery object you selected. In your case, the document. The ownerDocument value of document is null and this is what is passed through as document to the call to document.createDocumentFragment(); . Hence you get the error that document is null (Slightly bad naming of variables there as it makes you think the document object itself is somehow null)

As other people have said. Append to the body instead and it will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM