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
- NodeList: forEach() method: developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
- 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
- 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
- Adding a class to all sibling elements of a specific type in JavaScript
- Append an element after a specific element in JavaScript
- Click event only on parent, not children
- Detecting a newly generated element and adding a class to it in JavaScript
- Generating an HTML list out of page headings in JavaScript
- Getting the last class name in classList collection
- Run only once inside a loop