| home / programming / javascript / ppk2 |
|
|
There's one problem with createTextNode(): it cannot create HTML entities like © or —. Instead of the symbol you need, it creates the literal text:
createTextNode() cannot create HTML entities.
Use innerHTML instead:
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>.
cloneNode() has a couple of features you must know about in order to use it properly:
cloneNode() expects an argument true or false. true means "Clone the element and all its child nodes." false means "Clone the element but not its child nodes." In practice, you always use true; I have never yet encountered a situation in which you want to clone a node but not its children.cloneNode() does not clone event handlers. This is extremely annoying, but it's how the method was specified. (Why? I have no idea.) So every time you clone a node with event handlers, you have to redefine them on the clone.
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 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.
| home / programming / javascript / ppk2 |
URL: