Javascript forEach: How to iterate list items by Javascript?

You can iterate over given HTML list items using javascript by fetching li tags object with querySelectorAll()

Based on the response to the document.querySelectorAll() object, you need to convert the object to an array type that will be supported with forEach in javascript.

Let’s take a simple UL <LI> tag structure to fetch list items text value using forEach,

<ul class="site-social">
    <li class="site-social__item">Chat</li>
    <li class="site-social__item">Mail</li>
    <li class="site-social__item">Media</li>
</ul>

Now You can achieve it with a few lines of javascript,

let getLIitemsObject = document.querySelectorAll('.site-social li');

//convert Object to Array type
let liItems = Object.values(getLIitemsObject);

// Foreach over LI Items
liItems.forEach(function (data) {
    console.log('result ', data.innerHTML);
});

In the result, You will get List items text in the console.

You can use forEach on a simple array like the below,

let digitArray = [1, 2, 3];

digitArray.forEach(element => console.log('Number ', element));

// result will be Number 1, Number 2, Number 3