Material Box

Material Box

WEB Design & Material Images

JavaScript - Get index number with For loop

JavaScript

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

JavaScript - Get index number with For loop

TitleJavaScript - Get index number with For loop

CategoryJavaScript

Created

Update

AuthorYousuke.U