Section 2.4. DOM Methods


2.4. DOM Methods

In most scenarios that involve interacting with elements on an HTML page, using the special JavaScript document.forms object and its friends or using document.getElementById() with the innerHTML property suffices. Yet there are some cases where access to the DOM itself is required. Appendix B contains a complete list of supported methods for accessing the DOM. Here are some of the most important ones:


getElementsByTagName( name)

Returns an array with all elements of the given element name in the page


createElement( name)

Creates a new DOM node with the given element name


createAttribute( name)

Creates a new attribute for the node with the given attribute name


createTextNode( text)

Creates a new text DOM node (text within an element) with the given text


appendChild( node)

Appends the node as a child of the current element

Example 2-13 shows how to use some of these methods to recreate the preceding example, but this time by dynamically creating a new <span> element and a text node. In this example, the appendChild() method comes into play: first, the text child is added to the <span> element, and then the <span> element is added to the paragraph.

Example 2-13. Using DOM with JavaScript

 JavaScript-DOM.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>   <title>JavaScript</title>   <script language="JavaScript" type="text/javascript">   function ShowText(f) {     var paragraph = document.getElementsByTagName("p")[0];     var label = document.createElement("span");     var text = document.createTextNode(f.elements["TextBox1"].value);     label.appendChild(text);     paragraph.appendChild(label);   }   </script> </head> <body>   <form action="">     <input type="text" name="TextBox1" />     <input type="button" value="Show text" onclick="ShowText(this.form);" />     <p>Entered text: </p>   </form> </body> </html> 




Programming Atlas
Programming Atlas
ISBN: 0596526725
EAN: 2147483647
Year: 2006
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net