Created
August 22, 2019 16:23
-
-
Save parzibyte/84d4e8930730622ee90732728905ab67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Dibujar una tabla de HTML | |
* usando JavaScript puro | |
* | |
* @author parzibyte | |
* | |
* @see https://parzibyte.me/blog | |
*/ | |
const productos = [{ | |
id: 1, | |
nombre: "Mouse Logitech", | |
precio: 20, | |
codigo: "123", | |
}, | |
{ | |
id: 2, | |
nombre: "Xiaomi Mi A1", | |
precio: 5000, | |
codigo: "123444", | |
}, | |
{ | |
id: 3, | |
nombre: "Galletas", | |
precio: 10, | |
codigo: "20205", | |
}, | |
{ | |
id: 4, | |
nombre: "Computadora portátil", | |
precio: 30000, | |
codigo: "7700545", | |
}, | |
]; | |
// Ahora dibujamos la tabla | |
const $cuerpoTabla = document.querySelector("#cuerpoTabla"); | |
// Recorrer todos los productos | |
productos.forEach(producto => { | |
// Crear un <tr> | |
const $tr = document.createElement("tr"); | |
// Creamos el <td> de nombre y lo adjuntamos a tr | |
let $tdNombre = document.createElement("td"); | |
$tdNombre.textContent = producto.nombre; // el textContent del td es el nombre | |
$tr.appendChild($tdNombre); | |
// El td de precio | |
let $tdPrecio = document.createElement("td"); | |
$tdPrecio.textContent = producto.precio; | |
$tr.appendChild($tdPrecio); | |
// El td del código | |
let $tdCodigo = document.createElement("td"); | |
$tdCodigo.textContent = producto.codigo; | |
$tr.appendChild($tdCodigo); | |
// Finalmente agregamos el <tr> al cuerpo de la tabla | |
$cuerpoTabla.appendChild($tr); | |
// Y el ciclo se repite hasta que se termina de recorrer todo el arreglo | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment