The easiest way to learn about nodes is to start off by simply appending an element node (one which will contain a text node) to the end of your document. Scripts 12.1 and 12.2 allow the user to enter some data and click a button, and voila! a new paragraph is added to your page ( Figure 12.2 ).
| 1. | var newText = document.createTextNode (inText); We start by creating a new text node (called newText ) using the createTextNode() method, which will contain whatever text was found in textArea . |
| 2. | var newGraf = document.createElement ("p"); Next, we create a new element node using the createElement() method. While the node we're creating here is a paragraph tag, it could be any HTML container ( div , span , etc.). The name of the new element is newGraf . |
| 3. | newGraf.appendChild(newText); In order to put the new text into the new paragraph, we have to call appendChild() . That's a method of newGraf , which, when passed newText , puts the text node into the paragraph. |
| | |
| 4. | var docBody = document. getElementsByTagName("body")[0]; In order to add a new node into the body of our document, we need to figure out where the body is. The getElementsByTagName() method gives us every body tag on our page. If our page is standards-compliant, there should only be one. The [0] property is that first body tag, and we store that in docBody . |
| 5. | docBody.appendChild(newGraf); And finally, appending newGraf onto docBody (using appendChild() again) puts the user's new text onto the page. |