HTML and CSS Reference
In-Depth Information
Figure 15.14
Original text is modified using the
innerHTML
property.
To create new elements on the fly, the DOM provides the
createElement()
method, and
for new text, the
createTextNode()
method. Once you get a reference to the new element,
you must insert or append it to the document. If, for example, you have created a
p
ele-
ment as follows:
var pref = document.body.createElement("p");
you can now append the new element to the body as follows:
document.body.appendChild(pref);
Now we can add text to the new paragraph by using the
createTextNode()
method and
the
appendChild()
method as follows:
txt = document.createTextNode("Hello, new paragraph!");
And finally, we will append this text to the new paragraph as:
new_pref.appendChild(txt);
EXAMPLE
15.7
<html>
<head><title>Creating a New Element</title>
<style type="text/css">
.divStyle { background-color:blue;
border-style:solid;
color:white;
}
p{ color:yellow; font-size:150%;}
</style>
<script type="text/javascript">
// Create a new p element and append it to a div
1
window.onload=function(){
2
var para = document.createElement("p");
3
var divObj = document.getElementById("divtest");