+ 1

What is wrong with the following code?

var tr = document.createElement("tr"); var table = document.getElementsByTagName("table"); table.appendChild(tr); The JavaScript Console says: Uncaught TypeError: table.appendChild is not a function Line: 3

26th Jul 2017, 11:41 PM
Erik Johanson
Erik Johanson - avatar
1 Réponse
0
document.getElementsByTagName("table"); This line returns an array/collection of all table elements within the page. If there is only 1 element then you need to get the 0th element in the array and set that to table. var table = document.getElementsByTagName("table")[0]; var table = document.getElementsByTagName("table")[0]; var row1 = document.createElement("tr"); var row2 = document.createElement("tr"); var row1Cell1 = document.createElement("td"); var row1Cell2 = document.createElement("td"); var row2Cell1 = document.createElement("td"); var row2Cell2 = document.createElement("td"); row1Cell1.appendChild(document.createTextNode("R1C1")); row1Cell2.appendChild(document.createTextNode("R1C2")); row2Cell1.appendChild(document.createTextNode("R2C1")); row2Cell2.appendChild(document.createTextNode("R2C2")); row1.appendChild(row1Cell1); row1.appendChild(row1Cell2); row2.appendChild(row2Cell1); row2.appendChild(row2Cell2); table.appendChild(row1); table.appendChild(row2);
27th Jul 2017, 1:47 AM
ChaoticDawg
ChaoticDawg - avatar