MKD
MKD

Reputation: 799

Dynamically append Div in HTML JavaScript

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.

Upvotes: 0

Views: 12082

Answers (3)

itzmukeshy
itzmukeshy

Reputation: 1

Just replace first js code line with this one:-

function addNewRow(){

Upvotes: 0

Maulik patel
Maulik patel

Reputation: 1601

define javascript function like function addNewRow() { not a function addNewRow {

Upvotes: 0

Tibos
Tibos

Reputation: 27823

You 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.com/egImArO/1/edit

Upvotes: 2

Related Questions