2

I want to write into table, specifically the top row and the left columns like in chess where there are A1, A2, etc. How do I write into table rows[i].cells[j].--- . I'm just struggling with trying to write into table.

document.getElementById("Table").rows[i].cells[j]. ??? ;

Hey guys, so it's solved now. I use .textContent.

1
  • Please provide what you have tried so far Commented Feb 14, 2019 at 9:19

2 Answers 2

4

You can only do it in this fashion:

var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2"; 

or give ids to each cell and then insert values

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

Comments

1

You can do this using the querySelector method on the table with the nth-of-type selector method:

//Generate table
var table = document.createElement("table");
table.className = "table";
for (var y = 1; y <= 8; y++) {
  //Create row
  var row = table.insertRow();
  for (var x = 1; x <= 8; x++) {
    //Create cell
    var td = row.insertCell();
    if (x % 2 != y % 2) {
      //Set background to distinguish cells
      td.style.backgroundColor = "#EEE";
    }
    //Show coordinates on mouse hover
    td.title = x + ":" + y;
  }
}
//Insert into document
document.body.appendChild(table);
//Write to specific row
table.querySelector("tr:nth-of-type(" + 2 + ") td:nth-of-type(" + 5 + ")").textContent = "1";
table.querySelector("tr:nth-of-type(" + 5 + ") td:nth-of-type(" + 2 + ")").textContent = "2";
td {
  min-width: 50px;
  min-height: 50px;
  height: 50px;
  text-align: center;
}

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.