I'm trying to add 4 "tr" elements which each contain 4 "td" elements but I don't quite know how to do it. I can add single tr's with a single td but not multiple.
Here is my incomplete code. The problem is from where I have written "// HERE IS THE PROBLEM!!!". Any help is very much appreciated.
/* ///// INITIAL TITLE ///// */
var initialTitle = document.createElement("h1");
var intialTitleContent = document.createTextNode("Please press the \"1\" key on your keyboard.");
initialTitle.appendChild(intialTitleContent);
document.body.appendChild(initialTitle);
/* ///// KEYDOWN CODE ///// */
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.keyCode == "49") // "1"
{
var pElement = document.createElement("p");
var content = document.createTextNode("Welcome! This page is
made entirely out of javascript. It is completely impractical
to create a webpage in this manner. This page is simply a
demonstration of how javascript can be used to create and add
HTML elementS and CSS to a HTML document. You can add content
by pressing the \"1\" through to \"9\" keys.");
pElement.appendChild(content);
document.body.appendChild(pElement);
}
// HERE IS THE PROBLEM!!!
else if (key.keyCode == "50") // "2"
{
var i;
var tableDiv = document.createElement("div");
tableDiv.classList.add("div_1");
var tableElement = document.createElement("table");
var trElements = document.createElement("tr");
var tdElements = document.createElement("td");
tdElements.classList.add("tableCell");
for (i = 0; i < 4; i++) {
var multi =
tableDiv.appendChild(tableElement);
tableElement.appendChild(trElements);
trElements.appendChild(tdElements);
}
document.body.appendChild(multi);
<!doctype html>
<html lang="en-gb">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, intital-scale= 1.0" />
<title>Javascript Only Site</title>
</head>
<body>
<script src="JOS.js"></script>
</body>
</html>
trandtd) inside each loop iteration. Creating before the loop will use always the same memory location and will work with just one element