3

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.

1
  • setAttribute does not take a 3rd argument. What is the 0 and 1 you are passing in? Commented Jan 19, 2015 at 20:54

1 Answer 1

3

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.

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

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.