'Insert the 'html' tag before the 'head' tag (not in or between them) using JavaScript

I need to insert a comment before the 'html' tag and before the doctype tag (if present), like...

<!-- Hello, World! -->

From a previous quest, the following code did the job where an attribute was to be inserted "inside" a tag. However, this quest is different...

document.getElementsByTagName("html")[0].setAttribute("id", "something");

How can I insert "before" the nominated tag?



Solution 1:[1]

There aren't any guarantees about browser support, but this works in Firefox and Chrome:

var comment = document.createComment("HelloWorld");

document.insertBefore(comment, document.firstChild);

And FYI, you don't insert before "tags" after the HTML is parsed. You insert into the DOM before a DOM node.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen