Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Prepend: Cannot call method 'createDocumentFragment' of null

During page startup I'm trying to add an element to the DOM.

I have the following code:

$(document).ready(function () {
    $(document).prepend("<div id=new_div style=z-index:1;></div>");
});

I've tested this on FF21, Chrome27 and IE10. They all return the error mentioned in the title (exact wording is from the Chrome debugger).

Debugging on jquery-1.10.0.js, I tracked down the problem to line 5998 where

safeFrag = document.createDocumentFragment()

Apparently document is null. Going up the stack trace to domManip on line 6249 the object is passed as this[ 0 ].ownerDocument, which is null.

I've stripped the javascript on the page to just loading jQuery and running this command, and the issue persists.

See this jsFiddle, the alert doesn't pop, meaning the javascript engine got stuck on the line before.

Help appreciated.

like image 567
JNF Avatar asked May 28 '13 06:05

JNF


1 Answers

It doesn't make sense to try to add an element to the start of the document object. It isn't an HTMLElementNode. As far as I know, you can't give it additional children at all.

If you want to add a div element to the start of something, then the highest node that is allowed to contain it is the body element, so use:

$(document.body).prepend

… instead.

like image 124
Quentin Avatar answered Oct 01 '22 14:10

Quentin