icon picker
9. Dynamically Display HTML with a Loop

Use a `for` loop to build a string holding HTML, then display it on a web page.
Vamos a usar los siguientes archivos index.html css/style.css js/html-loop.js disponibles al final:

Esto es lo que intentaremos crear
Captura de Pantalla 2022-05-24 a la(s) 00.41.00.png

en js/html-loop.js
const main = document.querySelector('main'); // Elegirmos la etiqueta main dentro del HTML

let html = ' '; // aqu'i pondeemos los div

for (let i = 0; i < 10; i++) {
html += `<div>${i}</div>`
main.innerHTML = html;
}


Captura de Pantalla 2022-05-24 a la(s) 00.47.23.png
Notar que va del 0 al 9. Debemos depurar el código:
en js/html-loop.js
const main = document.querySelector('main'); // Elegirmos la etiqueta main dentro del HTML

let html = ' '; // aqu'i pondeemos los div

for (let i = 1; i <= 10; i++) {
html += `<div>${i}</div>`
main.innerHTML = html;
}
Ahora sí se obtuvo lo que se quería:
Captura de Pantalla 2022-05-24 a la(s) 00.52.16.png

Modificando el comportamiento

En el for podemos cambiar la condición de iteración y hacerlo hasta el 100
for (let i = 1; i <= 100; i++) {
html += `<div>${i}</div>`
main.innerHTML = html;
}
Captura de Pantalla 2022-05-24 a la(s) 00.54.17.png

Podríamos cambiar incluso el paso a paso
for (let i = 5; i <= 100; i+=5) {
html += `<div>${i}</div>`
main.innerHTML = html;
}
Captura de Pantalla 2022-05-24 a la(s) 00.57.46.png

Archivos del experimento

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Loops</title>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<main></main>
<script src="js/html-loop.js"></script>
</body>
</html>
css/style.css

body {
color: #fff;
font-family: "Gotham Rounded A", "Gotham Rounded B", "Gotham Rounded", "Helvetica Neue", Helvetica, Arial, sans-serif;
box-sizing: border-box;
background-color: #3f8abf;
}

main {
width: 90%;
max-width: 1080px;
padding: 40px 0 0;
margin: 0 auto;
}

main div {
color: #3f8abf;
font-weight: 500;
font-size: 1.25em;
text-align: center;
line-height: 58px;
width: 55px;
height: 55px;
display: inline-block;
background-color: white;
border-radius: 50%;
margin: 0.5em;
}

h1 {
font-size: 3.75em;
text-shadow: 0 2px 1px rgba(0,0,0, 0.15);
}

h2 {
font-size: 2.5em;
font-weight: normal;
}

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.