dev.rean.me
javascript

03 - JavaScript forEach Loop with DOM Elements (Video Tutorial in Khmer)

Learn how to use JavaScript forEach loop with DOM elements (querySelectorAll) to change styles, text, and add click events step-by-step with video tutorial in Khmer.

2026-08-28 · 3 min read

Share:

Hello my friend! Today I show you step-by-step how to use forEach() Loop with DOM Elements in JavaScript! When you have many HTML elements (like buttons, list items, or text cards), forEach() loop helps you loop through every element easily to change text, update styles, or add click events! Very easy to follow with code examples and video tutorial in Khmer! Let's get started!

JavaScript forEach with DOM Element speak khmer

Step 1: Select Multiple Elements (querySelectorAll)

First step, we need to select all HTML elements from web page. In JavaScript, we use document.querySelectorAll().

<!-- HTML structure -->
<button className="box-btn">Button 1</button>
<button className="box-btn">Button 2</button>
<button className="box-btn">Button 3</button>

In JavaScript, select all buttons:

// Returns a NodeList of all elements matching class '.box-btn'
const buttons = document.querySelectorAll(".box-btn");

💡 Tip: Remember difference! document.querySelector() selects only the 1st matching element on page. If you want to select ALL elements, always use document.querySelectorAll()!


Step 2: Loop Elements with forEach() to Change Text & Style

After selecting elements, use forEach() loop to iterate over each element in the list:

const buttons = document.querySelectorAll(".box-btn");

// Loop over every button
buttons.forEach((btn, index) => {
  // Change text content
  btn.textContent = `Card Button #${index + 1}`;

  // Change style color
  btn.style.backgroundColor = "#2563eb";
  btn.style.color = "#ffffff";
  btn.style.padding = "10px 16px";
  btn.style.borderRadius = "8px";
});

💡 Tip: forEach() gives you 2 main parameters: (element, index). element is current HTML element, and index is item counter starting from 0! You can use index + 1 to show user-friendly numbers (#1, #2, #3)!


Step 3: Add Click Event Listener to Multiple Buttons

One of the best uses of forEach() is adding event listeners (like click) to multiple buttons at once!

const buttons = document.querySelectorAll(".box-btn");

buttons.forEach((btn, index) => {
  btn.addEventListener("click", () => {
    alert(`You clicked button number ${index + 1}!`);
  });
});

💡 Tip: Never write addEventListener manually 10 times for 10 buttons! Always use querySelectorAll() + forEach() loop to attach event listeners dynamically in 3 lines of code!


Watch Video Tutorial (Khmer)

Watch full step-by-step video tutorial below to see complete live demo in Khmer:


Hope this tutorial help you understand how to use forEach() loop with DOM elements easily! Practice selecting elements and looping over them today. Happy learning my friends! Sharing is caring!

← Back to javascript
Share: