createTextNode

In this chapter you will learn:

  1. How to create text node for HTML element

Create new text node

In the following code it creates a new element tr and creates new text node for the new added element.

<!DOCTYPE HTML> <!--from   j a  va  2  s. c om-->
<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 access data attributes in 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