skip to Main Content

I am trying to add items from my array in javascript into my html list. I have gotten it where the array displays but my entire array displays in one bullet point on my list instead of each item on their own bullet points.

eg

•Sugar,Milk,Bread,Apples

instead of

•Sugar
•Milk
•Bread
•Apples
let myArray = ["Sugar", "Milk", "Bread", "Apples"]

arrayList = (arr) => {
    let list1 = document.querySelector("#itemList");
    let myListItems = document.createElement("li");
    myListItems.textContent = arr;
    list1.appendChild(myListItems)
}

arrayList(myArray)

2

Answers


  1. The issue is because you’re getting the text of all the array elements and putting them in to a single li.

    To fix the problem you need to loop through the array, creating a new li for each item within it:

    let myArray = ["Sugar", "Milk", "Bread", "Apples"];
    let list1 = document.querySelector("#itemList");
    
    arrayList = (arr) => {
      let items = arr.forEach(item => {
        let li = document.createElement('li');
        li.textContent = item;
        list1.appendChild(li)
      });
    }
    
    arrayList(myArray)
    <ul id="itemList"></ul>
    Login or Signup to reply.
  2. You need to loop through the array:

    <html>
    <body>
    <ul id="itemList">
    </ul>
    </body>
    <script>
    const myArray = ["Sugar", "Milk", "Bread", "Apples"]
    
    createLiAndAppend = (arr, listId) => {
        const list1 = document.getElementById(listId);
        const myListItems = document.createElement("li");
        myListItems.textContent = arr;
        list1.appendChild(myListItems);
    }
    
    myArray.forEach(m => createLiAndAppend(m, "itemList"));
    </script>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search