简体   繁体   中英

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.

Regards,
Dinesh

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

定义javascript函数,如函数addNewRow(){ not a function addNewRow {

Just replace first js code line with this one:-

function addNewRow(){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM