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:

html<input>

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

javascriptlet 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:

javascriptlet input = document.querySelector('input');

input.addEventListener('blur', function() {
  let num = +input.value;
  
  if (num > 0 && num <= 10) {
    console.log('+++');
  } else {
    console.log('---');
  }
});
Задание 1

The following code validates an entered value. Perform optimization:

html<input>
javascriptlet input = document.querySelector('input');

input.addEventListener('blur', function() {
  if (input.value === '1' || input.value === '2') {
    console.log('+++');
  } else {
    console.log('---');
  }
});
Задание 2

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

html<input>
javascriptlet input = document.querySelector('input');

input.addEventListener('blur', function() {
  let sum = 0;
  
  for (let i = 1; i <= +input.value; i++) {
    sum += i;
  }
  
  console.log(sum);
});
Задание 3

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

html<input>
<div></div>
javascriptlet 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;
    }
  }
});
Задание 4

The following code squares numbers from paragraphs. Perform optimization:

html<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
javascriptlet elems = document.querySelectorAll('p');

for (let elem of elems) {
  elem.textContent = elem.textContent * elem.textContent;
}
Задание 5

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

html<input data-min="5" data-max="10">
javascriptlet 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('---');
  }
});