TRAVEL

Surfing in Maldives

It’s windy. The cool breeze of the ocean. It gives, a sense of beauty, in motion. All is flowing, rushing and tide-And I sit in wonder, dreaming beside.

LEISURE

Outdoor
Experience

It’s windy. The cool breeze of the ocean. It gives, a sense of beauty, in motion. All is flowing, rushing and tide-And I sit in wonder, dreaming beside.

july 17, 2018

Document. documentElement

Why document. getElementsByClassName is different to document. querySelector(‘.className’).

javascript


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:

$(‘html’)


This is JQueries way of selecting the whole Html element.

Since I am relatively new to javascript I was about to use the generic querySelector*.

document. querySelector (‘.elementsClassName’)


So:

document. querySelector (‘html’)


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.