简体   繁体   中英

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

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

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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM