How to create a HTML element in Javascript
Create a new element
The following code creates a new element tr
and assign its id as newrow
when clicking the
button add
.
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 va 2 s . 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>