Optimization of work with DOM in JavaScript

Working with the DOM is a slow operation. Therefore, you need to minimize getting elements, reading and writing data, especially in a loop.

Let's look at an example. Suppose we have an input into which a number is entered:

<input>

Let's check that the entered number is in a given range when focus is lost:

let input = document.querySelector('input'); input.addEventListener('blur', function() { if (+input.value > 0 && +input.value <= 10) { console.log('+++'); } else { console.log('---'); } });

The problem is that we read a text from the input twice, although the number in it does not change. This is, of course, not optimal. We optimize:

let input = document.querySelector('input'); input.addEventListener('blur', function() { let num = +input.value; if (num > 0 && num <= 10) { console.log('+++'); } else { console.log('---'); } });

The following code validates an entered value. Perform optimization:

<input> let input = document.querySelector('input'); input.addEventListener('blur', function() { if (input.value === '1' || input.value === '2') { console.log('+++'); } else { console.log('---'); } });

The following code looks for the sum of integers from one to the number entered in the input. Perform optimization:

<input> let input = document.querySelector('input'); input.addEventListener('blur', function() { let sum = 0; for (let i = 1; i <= +input.value; i++) { sum += i; } console.log(sum); });

The following code looks for the sum of the divisors of the entered number. Perform optimization:

<input> <div></div> let input = document.querySelector('input'); input.addEventListener('blur', function() { let sum = 0; for (let i = 1; i <= +input.value; i++) { if (input.value % i === 0) { sum += i; let div = document.querySelector('div'); div.textContent = sum; } } });

The following code squares numbers from paragraphs. Perform optimization:

<p>1</p> <p>2</p> <p>3</p> <p>4</p> let elems = document.querySelectorAll('p'); for (let elem of elems) { elem.textContent = elem.textContent * elem.textContent; }

The following code checks that the input contains a string with a length in the given range. Perform optimization:

<input data-min="5" data-max="10"> let inp = document.querySelector('input'); inp.addEventListener('blur', function() { if (inp.dataset.min > inp.value.length || inp.dataset.max < inp.value.length) { console.log('+++'); } else { console.log('---'); } });
enru