Home > Enterprise >  How to add items as children of an unordered list using javascript
How to add items as children of an unordered list using javascript

Time:12-08

I'm trying to iterate over an array, and for each fruit, create a new list item, add the fruit name to the list item, and add the list item as a child of the unordered list.

let unorderedList = document.querySelector("grocery-list")
let fruits = ["apple", "banana", "kiwi", "mango"]
fruits.forEach(element => {
    document.getElementById("grocery-list").querySelector("li").innerHTML = element
});

This is what I currently have but it isnt adding them each as individuals its instead just turning the existing list item to "mango" so essentially overwriting itself until its at the end of the array. Below is the HTML of the page;

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <div id="groceries-section">
      <h1>Our Shopping List</h1>
      <ul id="grocery-list">
        <li>Milk</li>
      </ul>
    </div>
    <script src="main.js"></script>
  </body>
</html>

The expected output would be each item of the array as there an list item. I'm knew to this so any help is appreciated, thanks in advance

CodePudding user response:

You need to append a new LI for each item in the array, not overwrite the existing LI's contents.

let unorderedList = document.querySelector("#grocery-list")
let fruits = ["apple", "banana", "kiwi", "mango"]
fruits.forEach(element => {
  let newLI = document.createElement("li");
  newLI.innerText = element;
  unorderedList.appendChild(newLI);
});
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div id="groceries-section">
    <h1>Our Shopping List</h1>
    <ul id="grocery-list">
      <li>Milk</li>
    </ul>
  </div>
  <script src="main.js"></script>
</body>

</html>

CodePudding user response:

you are re-writing the same element every time, while you should create new items

let item = document.createElement('li');
item.innerHTML = element;
document.getElementById('grocery-list').appendChild(item);
  • Related