PPK on JavaScript: The DOM - Part 2/Page 2 | WebReference

PPK on JavaScript: The DOM - Part 2/Page 2

[previous] [next]

PPK on JavaScript: The DOM - Part 2

createTextNode() and HTML entities

There's one problem with createTextNode(): it cannot create HTML entities like © or —. Instead of the symbol you need, it creates the literal text:

Figure 8.10

Figure 8.10: createTextNode() cannot create HTML entities.

Use innerHTML instead:

Figure 8.11

Figure 8.11: Solution - use innerHTML.


The cloneNode() method clones a node; that is, it makes a near-exact copy of the node, which you can subsequently insert in the document tree. For instance:

I take the first <h1> in the document and clone it. Then I append the clone to the <body>.

Figure 8.12

cloneNode() has a couple of features you must know about in order to use it properly:

Sandwich Picker contains a useful example of all this. Every sandwich should have its own Order and Trash buttons, and of course these dozens of buttons are exactly the same. This is a typical job for cloneNode()!

At the start of the initialization function, I create one trashLink and one orderLink as template nodes. Note that I use innerHTML to create the link texts: I need a &nbsp; for CSS reasons, and createTextNode() doesn't allow me to insert it.

Later, when I go through all <tr>s in the order table, I clone these two templates, add the correct event handlers, and insert them into the document.

Every sandwich <tr> has a searchField form field. Since the buttons should appear underneath this form field, I append them to searchField.parentNode: the <td>.

Note that I assign the event handlers only after the buttons have been cloned. They would not survive the cloning process.

[previous] [next]