User Related
Let’s take a look at some of the methods associated with the window and document objects. We begin with two methods, each of which provides a means to talk to the user.
window.alert()
Even if you don’t realize it, you’ve seen the results of the window object’s alert method on many occasions. The window object, you’ll recall, is at the top of the DOM hierarchy, and represents the browser window that’s displaying your page. When you call the alert() method, the browser pops open a dialog displaying your message, along with an OK button. Here’s an example:
<script>window.alert("Here is my message");</script>
This is our first working example of the dot notation. Here we are calling the alert() method of the window object, so our object.method notation becomes window.alert.
document.write()
You can probably guess what the write method of the document object does, simply from its name. This method, instead of popping up a dialog, writes characters directly into the DOM of the document, as shown in this snapshot
<script>document.write("Here is another message");</script>
try yourselft...
<!DOCTYPE html> <html> <head> <title>Hello from JavaScript!</title> </head> <body> <script> alert("Hello World!"); </script> </body> </html>
Reading a Property of the document Object
You may recall from earlier in the section that objects in the DOM tree have properties and methods. You saw how to use the write method of the document object to output text to the page—now let’s try reading one of the properties of the document object. We’re going to use the document.title property, which contains the title as defined in the HTML <title> element of the page.
Edit hello.html in your text editor, and change the call to the window.alert() method:
alert(document.title);
Notice that document.title is NOT now enclosed in quotation marks—if it were, JavaScript would infer that we wanted to output the string “document.title” as literal text. Without the quote marks, JavaScript sends to the alert() method the value contained in the document.title property.