Tip: Minimize DOM access

Angelos Chalaris · JavaScript, Browser · Jun 12, 2021

DOM operations, including accessing the DOM, are generally slow. This is usually not a problem until you have to perform many DOM operations and your JavaScript application's performance starts to suffer. A very quick trick to increase performance is to store DOM elements or their values in local variables if you plan to access them multiple times.

// This is slow, it accesses the DOM element multiple times
document.querySelector('#my-element').textContent = 'hello';
document.querySelector('#my-element').hidden = false;

// This is faster, it stores the DOM element in a variable
const myElement = document.querySelector('#my-element');
myElement.textContent = 'hello';
myElement.hidden = false;

Note that, while this trick may come in handy, it comes with the caveat that if you later remove the DOM element and you still have it stored in a variable, the variable should be set to null to avoid potential memory leaks.

Recommended snippets & collections

  • Tips & Tricks

    Snippet collection

    A collection of quick tips and tricks to level up your coding skills one step at a time.

  • Render DOM element

    JavaScript, Browser

    Renders the given DOM tree in the specified DOM element.

  • Run function asynchronously

    JavaScript, Browser

    Runs a function in a separate thread by using a Web Worker.

  • Add multiple listeners

    JavaScript, Browser

    Adds multiple event listeners with the same handler to an element.