PPK on JavaScript: The DOM - Part 1/Page 6
[previous] [next]
PPK on JavaScript: The DOM - Part 1
D: Changing the document tree
The W3C DOM contains four methods for changing the document tree. You'll use appendChild()
and insertBefore()
often, and removeChild()
and replaceChild()
more rarely.
General rules
All four methods return a reference to a node they acted on. For instance, in Sandwich Picker, for each sandwich the user orders, I append a <tr>
to the order table:
I could also have done this:
Now the node is appended, and the return value of appendChild()
is assigned to newSandwich
, so that it contains a reference to the node. We rarely need this reference, and therefore usually don't assign the return value of the methods to a variable. Nonetheless, remember that these references are available; occasionally you'll need them.
The four methods are all defined on the parent node of the node you want to do something with. So if you want to remove node x
, you write:
The following simple HTML page will serve as an example during the explanation of the four methods:
[previous] [next]
URL: