↑
Main Page
Creating and manipulating nodes
To access the
<div />
element with the ID
“div1”
, you can use the
getElementsByTagName()
like this:
var oDivs = document.getElementsByTagName(“div”);
var oDiv1 = null;
for (var i=0; i < oDivs.length; i++){
if (oDivs[i].getAttribute(“id”) == “div1”) {
oDiv1 = oDivs[i];
break;
}
}
Or, you could use
getElementById()
like this:
var oDiv1 = document.getElementById(“div1”);
As you can see, this is a much more streamlined way to get a reference to a specific element.
Creating and manipulating nodes
So far, you’ve learned how to access various nodes inside of a document, but that’s just the beginning of
what can be done using the DOM. You can also add, remove, replace, and otherwise manipulate nodes
within a DOM document. This functionality is what makes the DOM truly dynamic.
Creating new nodes
The DOM
Document
has a number of methods designed to create various types of nodes, even though
the browser
document
object doesn’t necessarily support each of these methods in all browsers. The fol-
lowing table lists the methods included in DOM Level 1 and which browsers support each one.
Method
Description
IE MOZ OP SAF
createAttribute
Creates an attribute node with
X X
X –
(
name
)
the given
name
createCDATASection
Creates a CDATA Section with a – X
– –
(
text
)
text child node containing
tex
createComment
Creates a comment node
X X
X X
(
text
)
containing
text
createDocument
Creates a document fragment
X X
X X
Fragment()
node
createElement
Creates an element with a tag
X X
X X
(
tagname
)
name of
tagname
Table continued on following page
Internet Explorer 6.0 also returns an element if the given ID matches the
name
attribute of an element. This is a bug, and one that you should be very careful of.
173
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 173
Free JavaScript Editor
Ajax Editor
©
→