Search code examples
javascriptcreateelement

Create div within a cell in Javascript


I am having troubles creating a div after creating a cell dynamically using Javascript. My goal is to be able to add the exact same original table row and its contents below. Below is the HTML code:

      <table width="100%" id="processTable">
    <tr>
    <td id="ProcessDetails"><div id="description">Replace with description.</div>
    <div id="QuestionToAnswer"><b>Replace with a question answerable by YES or NO</b></div>
    </td>
        <td id="AvailableAnswersColumn">
        <p id="option1"><a href="#YES">YES</a></p>
        <p id="option2">NO: Proceed to next question</p>
        </td>
    </tr>
<!--Insert new table row if needed-->
    </table>
    <div id="footer">
    <input type="button" value="Insert Table Row" id="CreateRow" class="CreateRow" onclick="insertRow()" />
    </div>

Here is the Javascript

<script>
function insertRow() {
    var table = document.getElementById("processTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = //within this cell should be created the div ids "description" + "QuestionToAnswer";
    cell2.innerHTML = //within this cell should be created the paragraph with ids "option1" + "option2";;
    cell1.setAttribute("id", "ProcessDetails", 0);
    cell2.setAttribute("id", "AvailableAnswersColumn", 1);
}
</script>

Please help.


Solution

  • document.createElement will be your friend here.

    var div = document.createElement("div");
    div.innerHTML = "Replace with description.";
    cell1.appendChild(div);
    

    With document.createElement(<tagname>) you can create any html element you want with JavaScript code. You can append it to the cell by using appendChild. Since div in my example is an object and a reference to a DOM node after it gets appended you can set event handlers to it etc.