Why does chrome throw "Uncaught Error: NOT_FOUND_ERR: DOM Exception 8" here?

Hubro picture Hubro · Jan 7, 2011 · Viewed 41.9k times · Source

Below is the code for my YWA wrapper

var astr_ywascript = (document.createElement("script").type = "text/javascript").src = "http://d.yimg.com/mi/eu/ywa.js";
document.head.appendChild(astr_ywascript); // <- error on this line

It's run on page load, so it makes no sense that JS can't find the document head tag.

Any ideas?

Thanks


Opera throws this error on the same line. Uncaught exception: Error: WRONG_ARGUMENTS_ER Firebug says: document.head is undefined [Break On This Error] document.head.appendChild(astr_ywascript);

Answer

spender picture spender · Jan 7, 2011

In the line

(document.createElement("script").type = "text/javascript").src

you are setting the src property of a string. The assignment in parentheses returns the assigned value. You make the same mistake later in the line, ultimately assigning "http://d.yimg.com/mi/eu/ywa.js" to astr_ywascript

Split it out onto separate lines:

var el=document.createElement("script");
el.type="text/javascript"
el.src=...
document.head.appendChild(el);

Raw Javascript rarely behaves in the fluid way one gets used to with jQuery.

You might also want to get the head as follows:

document.getElementsByTagName("head")[0]