94Part IIJavaScript TutorialListing 8-3(continued) document.createElement() anddocument.createTextNode() methodsThe document.write()method (Free web hosts)

94Part IIJavaScript TutorialListing 8-3(continued)

document.createElement() anddocument.createTextNode() methodsThe document.write()method works on a piece of a Web page only while the page is load- ing into the browser the first time. Any subsequent invocation of the method erases the pageand writes a new page. But if you want to add to or modify a page that has already loaded, you need to call upon the Dynamic HTML capabilities of W3C DOM-compatible browsers. Your goal will be to add to, delete from, or replace sections of the node hierarchy of the docu- ment. Most element objects have methods to perform those actions (see more in-depth dis- cussion in Chapter 14). But if you need to add content, you ll have to create new element ortext nodes. The documentobject has the methods to do that. The document.createElement()method lets you create in the browser s memory a brandnew element object. To specify the precise element you wish to create, pass the tag name ofthe element as a string parameter of the method: var newElem = document.createElement( p ); You may also wish to add some attribute values to the element, which you may do by assign- ing values to the newly created object s properties, even before the element becomes part ofthe document. As you saw in Chapter 4 s object hierarchy illustrations, an element object frequently needstext content between its start and end tags. The W3C DOM way to create that text is to gener- ate a brand new text node via the document.createTextNode()method, and populate thenode with the desired text. For example: var newText = document.createTextNode( Greetings to all. ); The act of creating an element or text node does not, by itself, influence the document nodetree. You must invoke one of the various insertion or replacement methods (see Chapter 14) to place the new text node into its element and place the element into the document. Youlearn how to do this in the last tutorial chapter (Chapter 12). document.getElementById() methodYou met the document.getElementById() method in Chapter 4 when learning about the syntaxfor referencing element objects. This W3C DOM method is one you will use a lot. Get to knowits finger-twisting name well. Be sure to honor the upper- and lowercase spelling of this all- important method.

Leave a Reply