I have a question about dynamical row creating to existing HTML table. I am sorry, if question seems stupid, but I am beginner at JavaScript. Here is HTML table (I cannot change any HTML code here):
I have to add rows with JavaScript, but because I cannot add table id to HTML code, it's impossible to do it by insertRow() function. I have tried with this code, but it doesn't work (not even with getElementsByClassName('some-tab')). The rows are not created. Code:
var something = getElementsByTagName('table');
var tableca = something[0];
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
tableca.appendChild(tr);
}
document.body.appendChild(tableca);
<table class="some-tab">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td id="Username">Admin</td>
<td id="Description">STH STH STH!</td>
</tr>
</table>
Can anyone help me, please? Thank you very much! :D
Look at your browser's developer tools.
Uncaught ReferenceError: getElementsByTagName is not defined
getElementsByTagName
is a method of the document
object and of DOM element objects. It isn't a global.
Just edit the first line of your code.
var something = document.getElementsByTagName('table');
var tableca = something[0];
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
tableca.appendChild(tr);
}
document.body.appendChild(tableca);
<table class="some-tab">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td id="Username">Admin</td>
<td id="Description">STH STH STH!</td>
</tr>
</table>