Reputation:
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
document.newRow.appendChild(newInput);
document.newRow.appendChild(newInput2);
document.newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
Upvotes: 0
Views: 80
Reputation: 2919
U just need to add some text into it..otherwise you won't see it (unless you open the dev console).
Here is an example:
// Helpers
const createElement = el => document.createElement(el)
const createText = text => document.createTextNode(text)
// Create rows
const addStudentRows = students => {
const $body = document.querySelector('body')
const $table = createElement('table')
for (let i = 0; i < students;i++ ) {
let $td1 = createElement('td')
let $td2 = createElement('td')
$td1.appendChild(createText('Hello'))
$td2.appendChild(createText('World'))
let $tr = createElement('tr')
$tr.appendChild($td1)
$tr.appendChild($td2)
$table.appendChild($tr)
}
$body.appendChild($table)
}
// Event listener
document.querySelector('button')
.addEventListener('click', e => addStudentRows(1))
table {
margin-bottom: 10px;
}
table tr td {
padding: 10px;
border-right:1px solid #f0f0f0;
border-top: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
}
table tr td:first-child {
border-left:1px solid #f0f0f0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>Click here</button>
</body>
</html>
Upvotes: 0
Reputation: 2648
You can't access elements with body. you need to use DOM functions like getElementById etc.. if its a new created elements as in your loop you can append to them directly as below
var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
newRow.appendChild(newInput);
newRow.appendChild(newInput2);
newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
<button id="submitButton" >button</button>
Upvotes: 2