How to Create a Loop in HTML and JavaScript?

Estimated read time 1 min read

You can create a loop in HTML and JavaScript by using JavaScript’s for loop or forEach method.

Here’s an example of using a for loop to create a list of items:

<ul id="list">
</ul>

<script>
  let items = ['item 1', 'item 2', 'item 3'];

  let list = document.getElementById('list');

  for (let i = 0; i < items.length; i++) {
    let item = items[i];
    let li = document.createElement('li');
    li.innerHTML = item;
    list.appendChild(li);
  }
</script>

And here’s an example of using the forEach method to create a list of items:

<ul id="list">
</ul>

<script>
  let items = ['item 1', 'item 2', 'item 3'];

  let list = document.getElementById('list');

  items.forEach(function(item) {
    let li = document.createElement('li');
    li.innerHTML = item;
    list.appendChild(li);
  });
</script>

Both of these examples create a list of items, but the forEach method is generally considered to be more concise and easier to read.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply