HTML and CSS Reference
In-Depth Information
EXAMPLE 15.9
<html>
<head><title>Create Elements and Attributes with the DOM</title>
<style type="text/css">
p { font-style:arial;
color:darkblue;
font-size:18
}
</style>
</head>
<body>
<script type="text/javascript">
1
window.onload=function(){
// Create three paragraphs with text
2
for(var i=1; i <= 3; i++){
3
var aPara=document.createElement("p");
4
var aBR = document.createElement("br");
5
var theTXT1=document.createTextNode("Hello, world. ");
var theTXT2=document.createTextNode("I hope you're
enjoying this DOM stuff! ");
var theTXT3=document.createTextNode("I am paragraph " +
i +".");
6
aPara.setAttribute("id","aPara" + i) ;
// set id attribute for the p element
document.body.appendChild(aPara);
aPara.appendChild(theTXT1);
aPara.appendChild(aBR);
aPara.appendChild(theTXT2);
aPara.appendChild(aBR);
aPara.appendChild(theTXT3);
}
7
alert(document.getElementById("aPara1")) ;
}
</script>
</body>
</html>
EXPLANATION
1
When the page has completely been loaded, this anonymous function will be
called. Its function is to create three paragraphs with unique id s and text (see Fig-
ure 15.17).
2
The for loop will iterate three times to create the three paragraphs.
3
A reference to a new p element is created.
Search WWH ::




Custom Search