Suppose we have elements collected using this selector:

const elements = document.querySelectorAll('.element');

There are several ways to create a JavaScript loop that goes over these elements.

Method 1: The old way

for (let i = 0; i < elements.length; i++) {
	// The current element is available as "elements[i]".
}

Method 2: The new way

for (const element of elements) {
	// The current element is available as "element".
}

Method 3: forEach

elements.forEach((element) => {
	// The current element is available as "element".
});

A shorter version (without defining elements as a separate const):

document.querySelectorAll('.element').forEach((element) => {
	// The current element is available as "element".
});