JavaScript Editor JavaScript Debugger     JavaScript Editor 



Team LiB
Previous Section Next Section

Creating Nodes

Now that we know how to move around a tree and access its elements, it is time to discuss manipulation of the document tree by creating and inserting nodes. The DOM supports a variety of methods related to creating nodes as a part of the Document object, as shown in Table 10-4.

Table 10-4: DOM Methods to Create Nodes

Method

Description

Example

createAttribute(name)

Creates an attribute for an element specified by the string name. Rarely used with existing (X)HTML elements since they have predefined attribute names that can be manipulated directly.

myAlign = document.createAttribute
("align");

createComment(string)

Creates an HTML/XML text comment of the form <!-- string --> where string is the comment content.

myComment = document.createComment
("Just a comment");

createDocumentFragment()

Creates a document fragment that is useful to hold a collection of nodes for processing.

myFragment = document.createDocument
Fragment();
myFragment.appendChild
(temp);

createElement(tagName)

Creates an element of the type specified by the string parameter tagName.

myHeading = document.createElement
("h1");

createTextNode(string)

Creates a text node containing string.

newText = document.createTextNode(
"Some new text");
Note 

The DOM Level 1 also supports document.createCDATASection(string), document .createEntityReference(name), and document.createProcessInstruction(target,data), but these methods would not be used with typical (X)HTML documents. If CDATA sections were properly supported by browsers to mask JavaScript, however, you might see that particular method in use.

Creating nodes is easy enough if you have a good grasp of (X)HTML. For example, to make a paragraph you would use

newNode = document.createElement('p'); // creates a paragraph

It is just as easy to make text nodes:

newText = document.createTextNode("Something to add!");

However, we need to join these objects together and insert them somewhere in the document in order to accomplish any interesting tasks. For now, they simply sit in memory.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Debugger     JavaScript Editor


©