Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 and 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).

like image 917
Dave Carpeneto Avatar asked Nov 17 '25 06:11

Dave Carpeneto


1 Answers

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.

like image 163
Spectric Avatar answered Nov 18 '25 20:11

Spectric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!