0

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I have cleared it. But still show **Uncaught TypeError: Cannot call method 'appendChild' of undefined **...
0

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

Comments

0

Just replace first js code line with this one:-

function addNewRow(){

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.