KOMPX.COM or COMPMISCELLANEA.COM   

Accessing the first element in forEach loop (JavaScript)

Accessing the first element in forEach loop, while iterating over a NodeList in JavaScript:

Child 1
Child 2
Child 3

HTML code:


<div class="example">
	<div>Child 1</div>
	<div>Child 2</div>
	<div>Child 3</div>
</div>

JavaScript code:


<script>
document.querySelectorAll('.example div').forEach( function ( element, index ) {
	if ( index == 0 ) {
		element.setAttribute( 'style', 'font-weight: bold; color: #c00;' );
	}
});
</script>

Links

  1. NodeList: forEach() method: developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
  2. How to identify the first iteration in a for..in loop: stackoverflow.com/questions/18936732/how-to-identify-the-first-iteration-in-a-for-in-loop
  3. How can I reference index of array when iterating over NodeList?: stackoverflow.com/questions/74693864/how-can-i-reference-index-of-array-when-iterating-over-nodelist
Browser support
Windows
Edge 16.0+
Firefox 50.0+
Google Chrome 51.0+
Opera 38.0+
Linux
Firefox 50.0+
Google Chrome 51.0+
Opera 38.0+
iOS
Safari 10.0+
Android
Samsung Internet 5.0+
Chrome 51.0+
Firefox 50.0+
Opera 41.0+
More