chasekenyon chasekenyon -3 years ago 84
HTML Question

innerHTML = var writes to console instead of to page

When I try to use the following code, innerHTML writes to the dev console instead of replacing the page body with myTable.

document.getElementsByClassName('body').innerHTML = myTable;


myTable is simply a series of text items formatting into a table. I have tried using jQuery

$("body").html(myTable);


However, I am trying to do this exclusively in javascript due to complications.

Full code below:

var titleArray = [];
var descArray = [];
var myTable = "<table><thead><tr><th>Index</th><th>Item Name</th>
<th>Description</th></tr></thead><tbody>";

var doc = top.frames['bsscright'].document;
titleArray = doc.getElementsByTagName('dt');
descArray = doc.getElementsByTagName('dd');

for (var i = 0; i < titleArray.length; i++) {
myTable+="<tr><td>" + i + "</td>";
myTable+="<td>" + titleArray[i].innerText + "</td>";
myTable+="<td>" + descArray[i].innerText + "</td></tr>";
}

myTable+="</thead></table>";

document.getElementsByClassName('body').innerHTML = myTable;


Can anyone tell me why .innerHTML = simply outputs my table in text form to console, instead of writing my table to the page?

Answer Source

Use querySelector instead to get the first body class, which seems to be what you want.

document.querySelector('.body').innerHTML = myTable;

Otherwise you're setting the .innerHTML property of the collection returned instead of on a specific element.


Also, you could use template strings to make this nicer.

var doc = top.frames['bsscright'].document;
var titleArray = doc.getElementsByTagName('dt');
var descArray = doc.getElementsByTagName('dd');

var myTable = "<table><thead><tr><th>Index</th><th>Item Name</th>
<th>Description</th></tr></thead><tbody>";

for (var i = 0; i < titleArray.length; i++) {
  myTable += `<tr><td>${i}</td>
                  <td>${titleArray[i].textContent}</td>
                  <td>${descArray[i].textContent}</td></tr>`;
}

document.querySelector('.body').innerHTML = myTable+"</thead></table>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download