I'm learning JavaScript and got to the section in my book that described creating new DOM elements like tables, rows, and columns, so I wanted to create a table similar to the periodic table of elements that I could later go back to and fiddle with as I learned new things. My problem is that, from everything that I understand so far, this code should work. Except that it doesn't display anything, and there is nothing showing up in the console in FireFox v29.0.
Ideally, I wanted to create 7 rows (periods) and 18 columns (groups), and then display the elements that were associated at those locations in the table, and then try formatting it (for example, there are empty cells inserted between elements 1 and 18, since the only elements in that period are Hydrogen (1) and Helium (2). An example of this can be seen here: http://www.webelements.com/
However, my first task (creating a basic table) just doesn't seem to work, and either I'm using the wrong terminology or no one has posted about this before (and "javascript periodic table" links mostly to just things like http://www.webelements.com/). Any ideas on what I'm missing here?
<html>
<head>
<title>Periodic Table</title>
</head>
<body>
<script>
var periodicTable = createTable( 7, 18);
var period = 7;
var group = 18;
document.body.appendChild(periodicTable);
function createTable( period, group ) {
var elementId = 0;
var table = document.createElement('table');
for (var p = 1; p < period; ++p) {
var tr = table.appendChild(document.createElement('tr'));
for (var g = 1; g < group; ++g) {
var element = tr.appendChild(document.createElement('td'));
element.innerHTML = ++elementId;
}
}
return table;
}
</script>
</html>
Edit Based on the helpful comments below, I've changed the code to look like this:
<script>
var periodicTable = createTable( 7, 18);
document.body.appendChild(periodicTable);
function createTable( period, group ) {
var elementId = 0;
var table = document.createElement('table');
for (var p = 1; p < period; ++p) {
var tr = table.appendChild(document.createElement('tr'));
for (var g = 1; g < group; ++g) {
var element = tr.appendChild(document.createElement('td'));
element.innerHTML = ++elementId;
}
}
return table;
}
</script>