JavaScript - Get index number with For loop
A code example for getting index numbers using a For loop in JavaScript.
The HTML has multiple <div> tags with class "item" for confirmation.
<div class="item-container">
<p>Get index number with For loop.</p>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
The target elements are queried together with querySelectorAll()
.
Array.prototype.entries()
can be used in the for loop to get index numbers.
// Get all items
let items = document.querySelectorAll('.item');
for (const [index, item] of items.entries()) {
console.log(index);
}