Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
Chessjan Avatar asked Mar 05 '13 10:03

Chessjan


People also ask

How to get append value in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How to append dom element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.


1 Answers

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.

like image 178
jAndy Avatar answered Oct 04 '22 08:10

jAndy