Search code examples
javascriptdominnerhtml

How I can show a innerHTML inside another one?


Question: In this code I´m traying to show the local storage in DOM, how I can show the "li" of the second for inside of the "ul" in the first for?

to show it like this? :

<div id = "receta${[i]}">
      <h2>${recetasLocales[i].nombreReceta}</h2>
      <ul><li>${recetasLocales[i].ingredientes[n].nombre}</li></ul>
      <p>${recetasLocales[i].procedimiento}</p>
</div>

This is the code I wrote, if you see in the case both innerHTML obviouly will be separate and I dont want that.

mostrar.addEventListener('click', () => {

  let recetasLocales = JSON.parse(localStorage.getItem('recetasLocales'))

  for (let i = 0; i < recetasLocales.length; i++) {
    listaReceta.innerHTML +=`
    <div id = "receta${[i]}">
      <h2>${recetasLocales[i].nombreReceta}</h2>
      <ul></ul>
      <p>${recetasLocales[i].procedimiento}</p>
    </div>
    `
    for (let n = 0; n < recetasLocales[i].ingredientes.length; n++) {
      listaReceta.innerHTML += `
      <li>${recetasLocales[i].ingredientes[n].nombre}</li>
      `
    }
  }

Solution

  • Another way to do this kind of thing without concatenating strings all the time is to use document.createElement() and appendChild().

    Note this uses textContent which prevents XSS attacks as it is not parsed as HTML.

    See this minimal example.

    const someValues = [
      [1, 2],
      [1, 2],
      [1, 2],
      [1, 2],
    ];
    
    // create div which contains the lists
    const div = document.createElement("div");
    
    for (let i = 0; i < someValues.length; i++) {
      // create heading
      const heading = document.createElement("h2");
      heading.textContent = `My heading for element ${i}`;
    
      // create list
      const list = document.createElement("ul");
      for (let j = 0; j < someValues[i].length; j++) {
        const element = someValues[i][j];
        // create a new list item
        const listItem = document.createElement("li");
        listItem.textContent = element;
        // add list item to list
        list.appendChild(listItem);
      }
    
      // adding it all together
      div.appendChild(heading);
      div.appendChild(list);
    }
    
    document.addEventListener("DOMContentLoaded", function (event) {
      const content = document.getElementById("test");
      content.appendChild(div);
    });
    <div id="test"></div>