createElement

In this chapter you will learn:

  1. How to create a new HTML element

Create a new element

The following code creates a new element tr and assign its id as newrow when clicking the button add.

<!DOCTYPE HTML> <!--   j  a v a 2s .  co m-->
<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> 
<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>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to create text node for HTML element
Home » Javascript Tutorial » HTML Operation
HTMLElement
addEventListener
appendChild
attributes
classList
className
cloneNode
createElement
createTextNode
dataset
getAttribute
getElementsByTagName
hasAttribute
innerHTML
insertAdjacentHTML
insertBefore
isSameNode
outerHTML
onmouseout
onmouseover
removeEventListener