Tối ưu hóa thao tác với DOM trong JavaScript

Thao tác với DOM là một thao tác chậm. Vì vậy cần phải giảm thiểu việc lấy phần tử, đọc và ghi dữ liệu, đặc biệt là trong vòng lặp.

Hãy xem qua một ví dụ. Giả sử chúng ta có một ô input, trong đó nhập vào một số:

html<input>

Hãy kiểm tra khi mất tiêu điểm, số được nhập có nằm trong khoảng đã cho không:

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

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

Vấn đề là chúng ta đọc giá trị từ ô input hai lần, mặc dù số trong đó không thay đổi. Điều này, tất nhiên, không tối ưu. Hãy tối ưu hóa:

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

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

Đoạn mã sau kiểm tra giá trị được nhập. Hãy thực hiện tối ưu hóa:

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

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

Đoạn mã sau tìm tổng các số nguyên từ một đến số được nhập vào ô input. Hãy thực hiện tối ưu hóa:

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

Đoạn mã sau tìm tổng các ước số của số được nhập vào ô input. Hãy thực hiện tối ưu hóa:

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

Đoạn mã sau tính bình phương các số từ các đoạn văn. Hãy thực hiện tối ưu hóa:

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

Đoạn mã sau kiểm tra xem chuỗi nhập vào ô input có độ dài nằm trong khoảng đã cho không. Hãy thực hiện tối ưu hóa:

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('---');
  }
});