I was recently advised to use Document.documentElement when querying the DOM to get the html element.
This came about because I was refactoring an old code base to swop JQuery for vanilla JS. Doing this I saw:
This is JQueries way of selecting the whole Html element.
When a colleague told me this was bad for performance.
Document.querySelector is basically a search / find operation. It scans the whole document to find the given element then selects that one and holds it in memory.
To save the browser searching through the whole document, document.documentElement returns the root element of the document.
The root element is the sole parent element to all the other elements. The top level element.
In a Html document the <html> </html>.
This means that when the JS runtime environment executes the Document.documentElement it knows exactly where to go and doesn’t waste any time searching the whole DOM.
*I have since been told that there is a better way to query the DOM in terms of performance.