Main Page

createElement

Method
Description
IE MOZ OP SAF
createEntity
Creates an entity reference node – X
– –
Reference(
name
)
with the given
name
createProcessing
Creates a PI node with the
– X
– –
Instruction(
target
,
given
target
and
data
data
)
createTextNode(
text
)
Creates a text node containing
text
XX
X X
IE = Internet Explorer 6 for Windows, MOZ = Mozilla 1.5 for all platforms, OP = Opera 7.5 for all platforms,
SAF = Safari 1.2 for MacOS.
The most commonly used methods are
createDocumentFragment()
,
createElement()
, and
createTextNode()
; the other methods are either not useful (
createComment()
) or not supported by
enough browsers to be useful at this point in time.
createElement(), createTextNode(), appendChild()
Suppose you have the following HTML page:
<html>
<head>
<title>createElement() Example</title>
</head>
<body>
</body>
</html>
To this page, you want to add the following code using the DOM:
<p>Hello World!</p>
The
createElement()
and
createTextNode()
methods can be used to accomplish this. Here’s how.
The first thing to do is create the
<p/>
element:
var oP = document.createElement(“p”);
Second, create the text node:
var oText = document.createTextNode(“Hello World!”);
Next you need to add the text node to the element. To do this, you can use the
appendChild()
method,
which was briefly mentioned earlier in the chapter. The
appendChild()
method exists on every node
type and is used to add a given node to the end of another ’s
childNodes
list. In this case, the text node
should be added to the
<p />
element:
oP.appendChild(oText);
174
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 174


JavaScript EditorFree JavaScript Editor     Ajax Editor


©