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) ...

Get Programming Atlas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.