0

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);
}
1
  • I don't understand what you want, it will display in whatever order you list the data in the toDos list. If you're storing the data externally you'll want to attach it by some id you can use to insert it back in the same order. Commented Jun 7, 2021 at 3:06

2 Answers 2

2
  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>

Sign up to request clarification or add additional context in comments.

1 Comment

@AlirezaAhmadi Much appreciated.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.