You’re overwriting the element each time you assign to innerHTML
, not appending to it. You can’t construct HTML incrementally as you have with DOM methods, because every time you assign to innerHTML
it parses it as a complete HTML fragment.
You should instead append to a string, and assign to innerHTML
at the end.
function print() {
// console.log("?")
var time = Number(localStorage.getItem("time"))
// console.log(typeof time)
var nClass = Number(localStorage.getItem("nClass"))
var duration = localStorage.getItem("duration")
var subjectsRaw = localStorage.getItem("arr")
var subjects = JSON.parse(subjectsRaw)
var html = "<table border = 1>"
for (var i = 0; i < 5; i++) {
console.log('test')
html += "<tr>"
for (let j = 0; j < nClass; j++) {
console.log('test2')
html += '<td>' + subjects[Math.floor(Math.random() * subjects.length + 0)] + '</td>'
}
html += "</tr>"
}
html += "</table>"
document.getElementById("tt").innerHTML = html;
}
I’m trying to print table in HTML by using JavaScript. It just gives me a blank page when I try to print the table. Here’s my HTML code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="gen.js"></script>
<link rel="stylesheet" href = "index.css">
</head>
<body onload="print()">
<div id="tt"></div>
</body>
</html>
Here’s my JavaScript file:
function print(){
// console.log("?")
var time = Number(localStorage.getItem("time"))
// console.log(typeof time)
var nClass = Number(localStorage.getItem("nClass"))
var duration = localStorage.getItem("duration")
var subjectsRaw = localStorage.getItem("arr")
var subjects = JSON.parse(subjectsRaw)
document.getElementById('tt').innerHTML = "<table border = 1>"
for(var i = 0; i < 5; i++){
console.log('test')
document.getElementById('tt').innerHTML = "<tr>"
for (let j = 0; j < nClass; j++) {
console.log('test2')
document.getElementById('tt').innerHTML = '<td>' + subjects[Math.floor(Math.random() * subjects.length + 0)] + '</td>'
}
document.getElementById('tt').innerHTML = "</tr>"
document.getElementById('tt').innerHTML = "<br>"
}
document.getElementById('tt').innerHTML = "</table>"
EDIT: Used DOM to print now.
I changed to DOM it’s still showing blank page and no error in console. If I try to print something before table even that doesn’t show.