1

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>

2
  • 2
    you should create new elements (trand td) inside each loop iteration. Creating before the loop will use always the same memory location and will work with just one element Commented Sep 27, 2018 at 13:08
  • Example code: jsfiddle.net/khrismuc/q81d9ctw Commented Sep 27, 2018 at 13:13

5 Answers 5

2

You should create tdElement inside loop and then append into trElement. Also append trElement, tableElement to tableDiv outside of the loop.

window.onload = function()
{
  var tableDiv = document.createElement("div");
  var tableElement = document.createElement("table");
  var trElement = document.createElement("tr");
  
  tableDiv.classList.add("div_1");
  tableElement.setAttribute("border","1");
  
  for(var i = 1; i <= 4; i++)
  {
    var tdElement = document.createElement("td");
    
    tdElement.innerText = i;
    tdElement.classList.add("tableCell");
    trElement.appendChild(tdElement);
  }
  
  tableElement.appendChild(trElement);
  tableDiv.appendChild(tableElement);
  
  document.body.appendChild(tableDiv);
}
<html>
<body>
</body>
</html>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I knew I was close to the answer. I've never used "innerText" before so I'll have to look more into how that works. Cheers.
1

You can use innerHTML to do this more easily.

tableDiv.innerHTML = `
  <table>
    <tbody>
      <tr>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
      </tr>
      <tr>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
      </tr>
      <tr>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
      </tr>
      <tr>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
        <td class="tableCell"></td>
      </tr>
    </tbody>
  </table>  
`;

I like this approach, because it's clearer what the HTML will look like. Of course there's a cutoff when you have a lot of markup and it becomes impractical to deal with this way, but at this point it's probably worth looking into something like _.js templates anyway: https://lodash.com/docs#template

Comments

0

Or...

new Array(4)
    .fill(new Array(4).fill(0))
        .map(array => { 
            var td = document.createElement('tr'); 
            array.forEach(e => td.appendChild(document.createElement('td'))); 
            return td;  
            }).forEach(p => console.log(p))

Comments

0

You need to create new instances of the node elements to be added. Otherwise you end up adding the same instance of the element will be moved if you try to append it again.

For example, this will create a table with 4 rows and 4 columns:

const mainEl = document.getElementsByTagName('main')[0];
const tableEl = document.createElement('table');

while(tableEl.childNodes.length<4){
  let trEl = document.createElement('tr');
  while(trEl.childNodes.length<4){
    let tdEl = document.createElement('td');
    tdEl.innerHTML = `row: ${tableEl.childNodes.length+1}<br > col: ${trEl.childNodes.length + 1}`;
    trEl.appendChild(tdEl);
  }
  tableEl.appendChild(trEl);
}

mainEl.appendChild(tableEl);
table{
width: 100%;
}
td{
  padding: 10px;
  border: 1px solid #000;
}
<main>

</main>

Comments

0

Thank you everyone for your help. It's very much appreciated. From combining what I have learnt from all of you, this is how I have got it to work:

window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
    
// SECTION 1 - Paragraph explaining what this page is about and what to do.
    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 element and CSS to a HTML document. Meaning within the HTML document the <body> element only contains a link to the javascript code and what the javascript code has added. You can add content by pressing the \"1\" through to \"9\" keys. Each piece of content can then be styled by pressing the \"s\" key.");
        pElement.appendChild(content);
        document.body.appendChild(pElement);
    }
    
// SECTION 2 - TABLE
    else if (key.keyCode == "50") // "2"
    {
        var tableDiv = document.createElement("div");
        var tableElement = document.createElement("table");
        

        tableDiv.classList.add("div_1");
        for (var z = 1; z <= 4; z++) {
            var trElement = document.createElement("tr");
            
            tableElement.appendChild(trElement);
            
            for (var i = 1; i <= 4; i++) {
                var tdElement = document.createElement("td");

                tdElement.classList.add("tableCell");
                trElement.appendChild(tdElement);
            }
        }
        
        tableDiv.appendChild(tableElement);
        document.body.appendChild(tableDiv);   
    }
<!doctype html>
<html lang="en-gb">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, intial-scale= 1.0"/>
    <title>Javascript Only Site</title>
</head>
<body>

    <script src="js/JOS.js"></script>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.