Trying to build an HTML list

Why doesn’t this loop display anything? The title is displayed of course, but the for loop never seems to execute, or maybe I have the HTML output syntax wrong?

This is such a noob question, but I have been fighting it, searching it, trying variations of it, for hours.

viewof test = {
  const element = html`<h1>Test</h1><ul>`
  for(let i = 0; i < 7; i++) { 
    html`<li>Index: ${i}</li>`
  };
  `</ul>`
  return element;
}
1 Like

it’s because element isn’t combining the extra data and the way the data is being added is not right.

Looking at what you are trying to do, you need to build an html string, which is the html code you want to display and then parse that sting into html and return that parsed data.

viewof test = {
  let html_string = `<h1>Test</h1><ul>`
  
  for(let i = 0; i < 7; i++) {
    html_string += `<li>Index: ${i}</li>`
  };
  html_string += `</ul>`
  
  return html`${html_string}`
}
1 Like

You can also take advantage of Observable template literal html`` to compose your element like this

viewof test = {
  const lis = [];
  for (let i = 0; i < 7; i++) {
    lis.push(html`<li> Index: ${i} </li>`);
  }
  const element = html`<h1>Test</h1><ul>${lis}</ul>`;

  return element;
}

You can learn more about this

and

3 Likes

Or, in one go:

viewof test = html`<h1>Test</h1><ul>${
  Array.from({length: 7}, (_, i) => html`<li> Index: ${i}</li>`)
}</ul>`
3 Likes

Thanks everyone! Thank you also for pointing me to more documentation. Problem soved!

3 Likes