Cloning Elements


var newItem = oldItem.cloneNode(true); 

Instead of creating new nodes all over again, you can also clone an existing node. The cloneNode() method that every node has does this for you. You can decide whether to clone only the node and its attribute, or to clone all child nodes (and their child nodes and so on) as well. If you provide TRue as the parameter for cloneNode(), a so-called "deep copy" also copies children; false copies only the node itself.

Cloning Nodes (clone.html)

<script language="JavaScript"   type="text/javascript"> var nr = 1; function addItem(cloneMode) {   var list = document.getElementById("list");   var oldItem = list.firstChild;   var newItem = oldItem.cloneNode(cloneMode);   list.appendChild(newItem); } </script> <ul ><li><a href="http://www. samspublishing.com/">Item 1</a></li></ul> <input type="button" onclick="addItem(true);"   value="Clone all" /> <input type="button" onclick="addItem(false);"   value="Clone node only" /> 

When you click on the first button, the whole node (including subelements like the link and list item text) are copied; the second button clones only the node itself, generating a new but empty list item. Take a look at Figure 5.6 to see the difference.

Figure 5.6. Two ways to copy nodes.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net