How to create text node for HTML element with Javascript
Create new text node
In the following code it creates a new element tr
and creates new text
node for the new added element.
Example
<!DOCTYPE HTML>
<html>
<body>
<table border="1">
<thead>
<th>Name</th>
<th>Color</th>
</thead>
<tbody id="myBody">
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
</tbody>
</table> <!-- w w w . j a v a 2s.c o m-->
<button id="add">Add Element</button>
<button id="remove">Remove Element</button>
<script>
var tableBody = document.getElementById("myBody");
document.getElementById("add").onclick = function() {
var row = tableBody.appendChild(document.createElement("tr"));
row.setAttribute("id", "newrow");
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("X"));
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("Y"));
};
document.getElementById("remove").onclick = function() {
var row = document.getElementById("newrow");
row.parentNode.removeChild(row);
}
</script>
</body>
</html>