JavaScript Required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
Loops en JavaScript
1. What is a Loop?
2. while Loop
3. do while Loop
4. Add One to a Number with the Increment Operator (++)
5. Challenge Loop
6. Bewere of Infinite Loops!
7. Evaluación Loops
8. for loop
9. Dynamically Display HTML with a Loop
10. Exit a Loop
11. The refactor Challenge
12. Challenge Task
More
Share
Explore
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:
9. Dynamically Display HTML with a Loop
Esto es lo que intentaremos crear
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;
}
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:
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;
}
Podríamos cambiar incluso el paso a paso
for (
let i = 5; i <= 100; i+=5
) {
html += `<div>${i}</div>`
main.innerHTML = html;
}
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;
}
p {
font-size: 1.1em;
line-height: 1.5;
}
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.