0

Here is my unordered list that I am trying to append additional list items to.

<ul id="subreddits">
   <li class="my-subs"><strong>MY SUBREDDITS</strong></li>
 </ul>

Here is the javascript. I tried two methods. I tried to map the array and also use a function. I get an error saying that it cant append to something null. The variables in the array all have values which equal to their names as strings.

 const subReddit = [home, "-", popular,"-", all, "-", random, "-", users]

function subredditList() {
 const unorderedList = document.getElementById("subreddits");
 for(let i = 0; i < subReddit.length; i++) {
    let item = document.createElement("li");
    item.innerHTML = subReddit[i];
    unorderedList.appendChild(item);
}
}

subReddit.map((sub, index) => {
 const unorderedList = document.getElementById("subreddits");
for(let i = 0; i < subReddit.length; i++) {
    let item = document.createElement("li");
    item.innerHTML = subReddit[i];
    unorderedList.appendChild(item);
}
})

Thanks in advance for the help. I really appreciate you all.

1 Answers1

0

In your subreddit list, you don't need to store the -.

You can print a list with join specifying the separator (as shown below).

Clean your list then cycle over it, create li elements, and append them to the container as below:

const subReddit = ['home', 'popular', 'all', 'random', 'users'];
console.log(subReddit.join('-'));

const container = document.querySelector('#subreddits');
subReddit.forEach(sub => {
  const item = document.createElement('li');
  item.innerHTML = sub;
  container.appendChild(item);
});
<ul id="subreddits">
  <li class="my-subs"><strong>MY SUBREDDITS</strong></li>
</ul>
quirimmo
  • 9,161
  • 1
  • 24
  • 43