javascriptdomgoogle-chrome-extension

Modifying document.head has no effect, but document.body does


I'd like to start building the head for a document via JS. I'm able to do this for the body via the following from https://stackoverflow.com/a/41026918/64696 :

document.body = document.createElement("body");
document.body.innerHTML = "<p>Hello World!</p>";

... however I cannot seem to do the same thing for the head - calling document.head = document.createElement("head"); returns null.

Is this possible? Anything I'm missing?

Note that I'm using Chrome 134.0.6998.89 & attempting to do this via a Chrome extension that has "run_at": "document_start" (so at the time the script is called there really isn't anything in the document at all).


Solution

  • The behavior is caused by the fact that head is a read-only property of the Document interface, whilst body is not.

    On the other hand, doing something like document.head.innerHTML = "" will work because you are not changing the value of the property but an attribute of it.