• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 9. Using the document and body O... > Creating New Elements and Nodes

Creating New Elements and Nodes

You can use document methods such as createElement and createTextNode (in IE4+ and NS6+) to create and insert new elements in a document, using methods such as the insertBefore method, as we’ll see in Chapter 16. Actually, we’ve already put these methods to work a while ago in Chapter 6—see “The insertBefore Method” in that chapter. There, I created a new element, created a new text node to hold the text in the element, and then used insertBefore to insert the new element into the web page. Here’s what that code looked like (Listing 06-09.html on the web site):

<HTML> 
    <HEAD> 
        <TITLE> 
            Creating New Elements 
        </TITLE> 

        <SCRIPT LANGUAGE="JavaScript"> 
            <!--
            function addMore() 
            { 
                var newDiv, newTextField, newText
					newDiv = document.createElement("DIV")
					newTextField = document.createElement("INPUT")
					newTextField.type = "TEXT"
					newTextField.value = "Hello!"
					newText = document.createTextNode("Here is a new text field: ")
					newDiv.insertBefore(newText, null)
					newDiv.insertBefore(newTextField, null)
					document.body.insertBefore(newDiv, null) 
            } 
            // --> 
        </SCRIPT> 
    </HEAD> 

    <BODY> 
        <H1>Creating New Elements</H1> 
        <FORM> 
            <INPUT TYPE=BUTTON VALUE="Click Me!" ONCLICK="addMore()"> 
        </FORM> 
    </BODY> 
</HTML> 

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint