I have created a div in HTML and want to add inner div dynamically to it. Below is the code for HTML:
<div id="table">
<div class="row">
This is the Demo First row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
<div class="row">
This is the Demo Second row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
</div>
<input type="button" value="Add New Row" onclick="addNewRow()" />
My CSS is:
div {
border: 1px dotted red;
padding: 10px;
}
And I have done the JavaScript for it but it is not working. The JavaScript is:
function addNewRow {
var table = document.getElementById('table');
var rDiv = document.createElement('div');
table.appendChild(rDiv);
rDiv.innerHTML = "This is the Demo Third row Content.";
var c1Div = document.createElement('div');
rDiv.appendChild(c1Div);
c1Div.innerHTML = "Cell 1 Content";
var c2Div = document.createElement('div');
rDiv.appendChild(c2Div);
c2Div.innerHTML = "Cell 2 Content";
}
But when I executed it, the new rows are not added. Please guide me what I am missing.
I have created a div in HTML and want to add inner div dynamically to it. Below is the code for HTML:
<div id="table">
<div class="row">
This is the Demo First row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
<div class="row">
This is the Demo Second row Content.
<div class="cell1">
Cell 1 Content
</div>
<div class="cell2">
Cell 2 Content
</div>
</div>
</div>
<input type="button" value="Add New Row" onclick="addNewRow()" />
My CSS is:
div {
border: 1px dotted red;
padding: 10px;
}
And I have done the JavaScript for it but it is not working. The JavaScript is:
function addNewRow {
var table = document.getElementById('table');
var rDiv = document.createElement('div');
table.appendChild(rDiv);
rDiv.innerHTML = "This is the Demo Third row Content.";
var c1Div = document.createElement('div');
rDiv.appendChild(c1Div);
c1Div.innerHTML = "Cell 1 Content";
var c2Div = document.createElement('div');
rDiv.appendChild(c2Div);
c2Div.innerHTML = "Cell 2 Content";
}
But when I executed it, the new rows are not added. Please guide me what I am missing.
Share Improve this question edited Aug 4, 2022 at 16:01 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 18, 2013 at 14:13 MKDMKD 7992 gold badges11 silver badges15 bronze badges3 Answers
Reset to default 2You have a typo preventing the execution of the function.
The correct name is document.getElementById
(line 2 in JS).
You might want to enable the console (F12 IE debugger, Firebug, Developer Tools, etc) for debugging next time. These kinds of errors are very easy to spot.
Here is a working JsBin: http://jsbin./egImArO/1/edit
define javascript function like function addNewRow() { not a function addNewRow {
Just replace first js code line with this one:-
function addNewRow(){