StephenW
StephenW

Reputation: 183

Display an html ordered list of array items?

I have the list displaying, but not displaying in an HTML ordered list. I know I somehow need to create a <li> element and attach it to the array. I don't know how to attach the array of items to a <li> element. Here is my code thus far.

let toDos = ['walk cat', 'pet fish'];
let listItems;

for (let i = 0; i < toDos.length; i++) {
    let displayListItems = document.createElement('li');
    listItems = toDos[i];
    listContainer.append(listItems);
}

Upvotes: 0

Views: 922

Answers (2)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9923

You have three options to do that: innerText or innerHTML or textContent.

const listContainer = document.querySelector("ol");

let toDos = ['walk cat', 'pet fish'];
let listItems;

for (let i = 0; i < toDos.length; i++) {
    let displayListItems = document.createElement('li');
    listItems = toDos[i];
    displayListItems.innerHTML = listItems;
    //displayListItems.innerText = listItems; //or this one
    //displayListItems.textContent = listItems; //or this one
    
    listContainer.append(displayListItems);
}
<ol></ol>

And notice that listContainer.append(listItems); is incorrect and you have to append displayListItems.

Upvotes: 1

DecPK
DecPK

Reputation: 25408

  1. You just need to create a list item using document.createElement('li') as you are creating
  2. Add it's text using textContent
  3. Append the listItem using appendChild or append.

const listContainer = document.querySelector("ol");

let toDos = ['walk cat', 'pet fish'];
let listItems;

for (let i = 0; i < toDos.length; i++) {
  let displayListItems = document.createElement('li');
  listItems = toDos[i];
  displayListItems.textContent = listItems;
  listContainer.append(displayListItems);
}
<ol></ol>

Upvotes: 2

Related Questions