↑
Main Page
several methods
Here are the ways to access various parts of this document:
?
To access the link, refer to
document.links[0]
.
?
To access the image, refer to
document.images[0]
or
document.images[“imgHome”]
.
?
To access the form, refer to
document.forms[0]
or
document.forms[“frmSubscribe”]
.
Additionally, all the attributes of links, images, and so on all become properties of the objects. For exam-
ple,
document.images[0].src
is the code to get the
src
attribute of the first image.
Finally, several methods exist on the BOM
document
object. One of the most often used is the
write()
method or its sibling
writeln()
. Each of these methods accepts one argument, which is a string to write
to the document. The only difference is, as you might expect,
writeln()
adds a new line (
\n
) character
at the end of the string.
Both methods insert the string content in the location where it is called. The browser then treats the doc-
ument as if the string were part of the normal HTML in the page. Consider the following short page:
<html>
<head>
<title>Document Write Example</title>
</head>
<body>
<h1><script type=”text/javascript”>document.write(“this is a
test”)</script></h1>
</body>
</html>
The page is displayed in the browser as if it were the following:
<html>
<head>
<title>Document Write Example</title>
</head>
<body>
<h1>this is a test</h1>
</body>
</html>
You can use this functionality to dynamically include external JavaScript files as well. For example:
<html>
<head>
<title>Document Example</title>
<script type=”text/javascript”>
document.write(“<script type=\”text/javascript\” src=\”external.js\”>”
+ “</scr” + “ipt>”);
</script>
</head>
<body>
</body>
</html>
151
JavaScript in the Browser
08_579088 ch05.qxd 3/28/05 11:37 AM Page 151
Free JavaScript Editor
Ajax Editor
©
→