PPK on JavaScript: The DOM - Part 1/Page 7
[previous] [next]
PPK on JavaScript: The DOM - Part 1
appendChild()
The appendChild()
method allows you to append a node as the last child of an element. If the node you append is already present in the document, it is removed from its current position. The node retains all its child nodes; these are also moved to the new position.
Example:
Of course you can also append text nodes:
Now the text node 'Hello World!' is removed from the <h1>
and appended as the last child of the second <p>
.
Return value
appendChild()
returns a reference to the appended node:
Now x contains a reference to node z.
Example
I use appendChild()
many times in the example scripts. Take, for instance, this function from Sandwich Picker:
The extra button says 'Collect all orders', and it should appear when the user has ordered sandwiches but hasn't yet moved them to the order table. I prepared the extraButton node in advance (we'll discuss that in the next section), and now I append it to the <td>
with ID="extrabuttonTarget".
insertBefore()
The insertBefore()
method allows you to insert a node before another node, and therefore you use it every time you want to append a child but don't want it to become the last child. Just as with appendChild()
, if the inserted node is already present in the document, it is removed from its current position, and the inserted node retains all its child nodes.
Now the first <p>
becomes the <body>
's first child. The <h1>
remains in the document, but now appears between the paragraphs. As before, it retains its child text node.
Return value
insertBefore()
returns a reference to the inserted node:
Now x
contains a reference to z
.
Example
I use insertBefore()
less often than appendChild()
, but still quite a lot. For instance, take this line from Usable Forms:
When a form field that was initially hidden should return to the visible form, I insert it before its insert point. (This insert point is a marker that exists only to mark the point where the <tr>
should be inserted, and it is a <tr>
, too. We'll discuss markers in Section8L.) I first move to the parent node of the insert point <tr>
and execute insertBefore()
from there.
[previous] [next]
URL: