Create a table using DOM with 2x2 cells - DOM functions

0

I am making a table of 4 squares, 2x2, and I have created the elements by means of DOM, only DOM functions can be used.

Why does not the table generate me?

HTML Code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>Animales!</title>
        <link rel="stylesheet" href="style/estilo.css"/>
        <script type="text/JavaScript" src="js/animales.js"></script>
    </head>

    <body>

    </body>
</html>

Javascript Code / DOM:

/*Registro un evento para cuando termine de cargarse el documento se cargen los eventos necesarios.*/
window.onload = crearTabla();

/*Exclusivamente con DOM, crear una tabla 2x2 (4 elementos-casillas).*/
function crearTabla() {
    //Obtener la referencia del elemento body.
    var body = document.getElementsByTagName("body")[0];

    //Crea un elemento <table> y un elemento <tbody>.
    var tabla = document.createElement("table");
    var tblBody = document.createElement("tbody");

    //Crea las celdas.
    for (var i=0; i<2; i++) {
        //Crea las hileras de la tabla.
        var hilera = document.createElement("tr");
        for (var j=0; j<2; j++) {
            var celda = document.createElement("td");
            var textoCelda = document.createTextNode("Hilera "+i+", Columna "+j);
            celda.appendChild(textoCelda);
            hilera.appendChild(celda);
        }
        //Agrega la hilera al final de la tabla (al final del elemento tblbody).
        tblBody.appendChild(hilera);
    }

    //Posiciona el <tbody> debajo del elemento <table>.
    tabla.appendChild(tblBody);
    //appends <table> into <body>.
    body.appendChild(tabla);
    //Modifica el atributo "border" de la tabla y lo fija a "2";
    tabla.setAttribute("border", "2");
}
    
asked by omaza1990 30.05.2017 в 20:23
source

1 answer

1

The problem is that you are executing the function crearTabla and you are assigning them to the property onload of window : window.onload = crearTabla(); .

You should assign the function and not the result: window.onload = crearTabla;

    
answered by 30.05.2017 / 20:36
source