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? :
JavaScript
x
6
1
<div id = "receta${[i]}">
2
<h2>${recetasLocales[i].nombreReceta}</h2>
3
<ul><li>${recetasLocales[i].ingredientes[n].nombre}</li></ul>
4
<p>${recetasLocales[i].procedimiento}</p>
5
</div>
6
This is the code I wrote, if you see in the case both innerHTML obviouly will be separate and I dont want that.
JavaScript
1
19
19
1
mostrar.addEventListener('click', () => {
2
3
let recetasLocales = JSON.parse(localStorage.getItem('recetasLocales'))
4
5
for (let i = 0; i < recetasLocales.length; i++) {
6
listaReceta.innerHTML +=`
7
<div id = "receta${[i]}">
8
<h2>${recetasLocales[i].nombreReceta}</h2>
9
<ul></ul>
10
<p>${recetasLocales[i].procedimiento}</p>
11
</div>
12
`
13
for (let n = 0; n < recetasLocales[i].ingredientes.length; n++) {
14
listaReceta.innerHTML += `
15
<li>${recetasLocales[i].ingredientes[n].nombre}</li>
16
`
17
}
18
}
19
Advertisement
Answer
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.
JavaScript
1
35
35
1
const someValues = [
2
[1, 2],
3
[1, 2],
4
[1, 2],
5
[1, 2],
6
];
7
8
// create div which contains the lists
9
const div = document.createElement("div");
10
11
for (let i = 0; i < someValues.length; i++) {
12
// create heading
13
const heading = document.createElement("h2");
14
heading.textContent = `My heading for element ${i}`;
15
16
// create list
17
const list = document.createElement("ul");
18
for (let j = 0; j < someValues[i].length; j++) {
19
const element = someValues[i][j];
20
// create a new list item
21
const listItem = document.createElement("li");
22
listItem.textContent = element;
23
// add list item to list
24
list.appendChild(listItem);
25
}
26
27
// adding it all together
28
div.appendChild(heading);
29
div.appendChild(list);
30
}
31
32
document.addEventListener("DOMContentLoaded", function (event) {
33
const content = document.getElementById("test");
34
content.appendChild(div);
35
});
JavaScript
1
1
1
<div id="test"></div>