HTML and CSS Reference
In-Depth Information
EXAMPLE 15.12
<html>
<head><title>Cloning Nodes</title>
<style>
p { font-family: cursive ;
background-color: yellow;
border-style:solid;
border-width:2px;
border-color:blue;
}
</style>
<script type="text/javascript">
1
function addPara(mode) {
2
var p1 = document.getElementById("para1");
3
var oldPara=p1.firstChild;
4
newPara=oldPara.cloneNode(mode);
5
p1.appendChild(newPara);
}
</script>
<head>
<body>
6
<p id="para1">
The news is so fabulous, I need to shout it out again! You
won the lottery!<br />
</p>
7
<input type="button" onClick="addPara(true); "
value="Clone me" />
</body>
</html>
EXPLANATION
1
The purpose of the addPara() function is to clone the text in a paragraph.
2
We get a reference to the paragraph that will be cloned.
3
The firstChild contains the contents or text of the paragraph.
4
Now a new paragraph is created, an exact replica of the old paragraph. It is a re-
cursive copy, so all child nodes will be copied as well.
5
To make the clone a real part of the document, it is appended to the first para-
graph.
6
This is the paragraph that will be cloned. It is given an id to reference it in the
function on line 2.
7
When the button is clicked, the addPara() function is called with the Boolean val-
ue true, which will be used to make a deep copy of the first paragraph. See Figures
15.22 and 15.23.
Search WWH ::




Custom Search