Java Reference
In-Depth Information
Try It Out Creating HTML Elements and Text with DOM Methods
You'll create a web page with just paragraph <p/> and heading <h1/> elements, but instead of HTML
you'll use the DOM properties and methods to place these elements on the web page. Start up your pre-
ferred text editor and type the following:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 12: Example 3</title>
</head>
<body>
<script type=”text/javascript”>
var newText = document.createTextNode(“My Heading”);
var newElem = document.createElement(“h1”);
newElem.appendChild(newText);
document.body.appendChild(newElem);
newText = document.createTextNode(“This is some text in a paragraph”);
newElem = document.createElement(“p”);
newElem.appendChild(newText);
document.body.appendChild(newElem);
</script>
</body>
</html>
Save this page as ch12_examp3.htm and open it in a browser (Figure 12-10).
It all looks a bit dull and tedious, doesn't it? And yes, you could have done this much more simply with
HTML. That isn't the point, though. The idea is that you use DOM properties and methods, accessed
with JavaScript, to insert these features. The fi rst two lines of the script block are used to defi ne the
variables in your script, which are initialized to hold the text you want to insert into the page and the
HTML element you wish to insert.
var newText = document.createTextNode(“My Heading”);
var newElem = document.createElement(“h1”);
You start at the bottom of your tree fi rst, by creating a text node with the createTextNode() method.
Then use the createElement() method to create an HTML heading.
At this point, the two variables are entirely separate from each other. You have a text node, and you have
an <h1/> element, but they're not connected. The next line enables you to attach the text node to your
HTML element. You reference the HTML element you have created with the variable name newElem , use
the appendChild() method of your node, and supply the contents of the newText variable you created
earlier as a parameter.
newElem.appendChild(newText);
Search WWH ::




Custom Search