i want to use js to add one row in an exsiting table,however i got an error:document.getElementById() is null,here is my code:
<!DOCTYPE html>
<html>
<head>
<title>use js to create one row</title>
</head>
<body >
<tr id="table">
<td>row 1</td>
</tr>
<script>
window.onload = function(){
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.getElementById("table");
tr.appendChild(rows);
}
</script>
</body>
</html>
i want to use js to add one row in an exsiting table,however i got an error:document.getElementById() is null,here is my code:
<!DOCTYPE html>
<html>
<head>
<title>use js to create one row</title>
</head>
<body >
<tr id="table">
<td>row 1</td>
</tr>
<script>
window.onload = function(){
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.getElementById("table");
tr.appendChild(rows);
}
</script>
</body>
</html>
Share
Improve this question
asked Dec 1, 2016 at 9:33
GxpGxp
351 gold badge1 silver badge6 bronze badges
2
-
rows
is undefined in your code, andtr
is invalid outside of atable
. – T.J. Crowder Commented Dec 1, 2016 at 9:34 - 1 first learn table structure and basic javascript and do some research and then ask a question at here. you could search on google for table structure : table structure in html and you could ask google : how to add a row in a table using javascript – Syed Ali Commented Dec 1, 2016 at 9:41
1 Answer
Reset to default 4Because tr
is invalid outside of a table, the browser is basically ignoring the tr
element entirely and just putting the text row 1
directly in body
, which is why getElementById
didn't return an element; it was never created by the browser when parsing the HTML.
Put the tr
in a table
(and ideally in a tbody
):
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
and append to the tbody
, being sure to create a row (tr
) as well as a td
since your apparent goal is to add a row:
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
It's also almost never useful to use the load
event on window
, since it doesn't get run until very late in the page-load process (waiting for all other resources, including all images, to load); that delay means the user can easily start interacting with your page before your code has run. Instead, use modules (which are run as soon as the DOM is in place, but not before) or just put your script at the very end of the HTML, just before the closing </body>
tag.
Live example:
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
<script>
(function() {
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
})();
</script>