The window Object

The browser creates a window object to hold information about the browser and a window object for each tab of the browser.

Window Properties and Methods

There are many properties and methods available in the window object.   All properties and methods of the window object are global.  That is you don’t need to reference them using the window object.  For example the window object has a property named console.  We’ve already used the console object by accessing it directly when we’ve called its log() method.  Another property of the window object is named document and is the root node in the DOM.

console.log(document.nodeType);  // 9

Adding Window Properties

Earlier when talking about variables we said that a variable declaration that doesn’t include the var keyword is global.  In fact, a variable that doesn’t include the var keyword becomes a property of window.

Properties that are added to the window object via a local variable cannot be deleted, but objects explicitly defined as window properties can be.

var age = 29; 
delete window.age;         // returns false.
 
window.color = “red”; 
delete window.color;       // returns true

Dialog Methods

There are three dialog methods that are properties of the window object: alert(), confirm(), and prompt().  Dialogs are synchronous and modal, meaning that execution of the JavaScript stops until the dialog has been dismissed.

The alert(message) method takes a string as an argument.  When executed, the method displays the string in a dialog box with one button labeled “OK”.

alert("Out of power");

The confirm(message) takes a string as an argument and returns a boolean.  When executed, the method displays the string in a dialog box with two buttons labeled “Cancel” and “OK”.  If the user presses OK, the method returns true and returns false otherwise.

var result = confirm("Update record?");
if (result == true) {
    ...
}

The prompt(message, default) takes two strings as arguments.  When executed, the method displays the first string (message) above an editable text box in a dialog box with two buttons labeled “Cancel” and “OK”.  The string in the second argument is used to pre-populate the text box.  When the user presses OK, the method returns the string remaining in the text box.

var result = prompt("Enter age", "19");

Opening and Closing Windows

The window.open() method opens a new window and returns a reference to the new window.  The method accepts 3 arguments:

  • a URL to load (required)
  • a window name (required)
  • a string of features (optional)

The third argument is a comma separated list of features expressed as name=value. See the documentation for a list of features and browser support.

window.open("http://techcrunch.com", "_blank", "width=600,height=400,top=100,left=100");

The window.close() method closes the referenced window.

var win = window.open("http://techcrunch.com", "_blank");
alert("pause");
win.close();

Print

The print() method brings up the browser’s print dialog.

The Location Object

The location object provides information about the document that is currently loaded in the window and provides general navigation functionality.  Some of the properties available in the location object are given below.

  • location.href
  • location.protocol
  • location.host
  • location.pathname
  • location.search
  • location.port

Manipulating the Location

The location can be changed by modifying the location.href property as shown below.

location.href = “http://slashdot.org”;

You can also modify the page loaded by modifying the other location properties (e.g. pathname).

location.pathname = "/work/teaching";

The location.replace(URL) method changes the location but doesn’t put an entry in the history stack.

location.replace("http://slashdot.org");

The Navigator Object

All browsers support the navigator object but its properties differ between browsers.  The navigator object specifies information about the browser, the client, etc.

console.log(navigator.appName + "," + navigator.platform);

The Screen Object

The window.screen object holds information about the screen hardware of the client computer.

The History Object

The history object represents the user’s navigation history.

history.go(-3);                     //go back one page
history.go(“http://n0code.net”);    //go to nearest URL page in history
history.back();                     // go back

DOM Nodes

The Document Object Model (DOM) is a model for HTML documents that represents the document as a tree of nodes containing elements, attributes and content.  The DOM is completely cross-browser compatible.

Node Relationships

Human family relationship names are used to describe relationships between nodes in the DOM.  For example, we say the <head> and the <body> elements are children of the <html> element and that the <html> element is the parent of the <head> and <body> elements.

Each node has read-only properties (given below) that allow access to various other nodes that have a relationship to it.

  • ownerDocument
  • parentNode
  • previousSibling
  • nextSibling
  • childNodes
  • firstChild
  • lastChild

The relationships for these properties is illustrated in the diagram below.

Each of these properties holds either null, a reference to another node in the tree or in the case of childNodes, a reference to a NodeList containing references to nodes.  The properties ownerDocument, parentNode, previousSibling, nextSibling, firstChild, and lastChild may be null.  The ownerDocument property points to the document’s root node and is null for the root node.

The childNodes property contains a (possibly empty) NodeList object. A NodeList is an ordered list whose elements are accessible by position in the same way elements in an array are accessible.  A NodeList object also has a length property which can be used to determine the number of children that a node has.

var node = ...

var len = node.childNodes.length;            
for (var i = 0; i < len; i++) {
    var child = node.childNodes[i];
    ...
}

The hasChildNodes() method returns true if childNodes.length > 0, false otherwise.

Node Properties

The DOM contains ALL of the information necessary to render a web page.  With JavaScript, we can inspect the DOM and manipulate the DOM causing the page to change without being reloaded.

To see the plethora of information stored in the DOM run the JavaScript shown below in a simple web page.  Try it on jsbin.com.  The window.document property holds the root node of the DOM tree. The function named recursivePrintChild() traverses the entire tree and prints out all of the information stored in each node of the tree.

var doc = window.document;
recursivePrintChild(doc);

function recursivePrintChild(node) {
    var len = node.childNodes.length;
    for (let i = 0; i < len; i++) {
        console.log(node.childNodes[i]);
        recursivePrintChild(node.childNodes[i]);
    }
}

nodeType, nodeName, and nodeValue

Each node in the DOM is an object and has a type; each type having its own properties and methods.  All node types inherit from the Node type, which defines a set of methods that all types must implement.

Every node has a nodeType property that holds a Number to indicate the type of node that it is.

  • ELEMENT_NODE (1)                                        <html><head><body>…
  • ATTRIBUTE_NODE (2)
  • TEXT_NODE (3)                                                    “hello world”
  • CDATA_SECTION_NODE (4)
  • ENTITY_REFERENCE_NODE (5)
  • ENTITY_NODE (6)
  • PROCESSING_INSTRUCTION_NODE (7)
  • COMMENT_NODE (8)
  • DOCUMENT_NODE (9)                                       window.document
  • DOCUMENT_TYPE_NODE (10)                         <!DOCTYPE html>
  • DOCUMENT_FRAGMENT_NODE (11)
  • NOTATION_NODE (12)

Each node also has a nodeName and nodeValue property.  Their semantics of these properties depend on the node’s type.  For element nodes, the nodeName is equivalent to the tag name of the element.  For text node, the nodeName is “#text”.

Below is script code that prints the nodeType and nodeName for each node in the tree.  As it traverses the DOM it adds tabs to the beginning of the output string so you see the hierarchy of the tree.

var doc = window.document; 
recursivePrintChild(doc, 0); 

function recursivePrintChild(node, level) { 
    var len = node.childNodes.length; 
    for (let i = 0; i < len; i++) {
        var type =node.childNodes[i].nodeType;
        var name = node.childNodes[i].nodeName;
        var prefix = '';
        for (let j = 0; j < level; j++) {
            prefix += '\t\t';
        }
        console.log(prefix + "(" + type + ") " + name); 
        recursivePrintChild(node.childNodes[i], level + 1); 
    } 
}

When you run the script you see that most of the nodes in the tree are element and text nodes. Which makes sense.  But there seems to be extra text nodes where no text appears in the HTML.  Well actually, the text is there, in the form of whitespace (spaces, tabs, and new line characters).  Any whitespace between HTML elements will be represented in the DOM as a #text nodes.  If you delete the whitespace from the HTML the number of DOM nodes is lessened considerably.

When we print the nodeValue property for each element, we see that the entire document’s HTML, CSS, and JavaScript text is stored in the DOM.  Below is a script that will show you the text stored in the DOM.

var doc = window.document; 
recursivePrintChild(doc);

function recursivePrintChild(node) { 
    var len = node.childNodes.length; 
    for (let i = 0; i < len; i++) {
        var name = node.childNodes[i].nodeName;
        var value = node.childNodes[i].nodeValue;
        console.log("(" + name + ")" + value); 
        recursivePrintChild(node.childNodes[i]); 
    }
}

When running the script we see that the only nodes with that have a non-null nodeValue property are text nodes.

The document Object

The document object is a property of the window object and so is accessible globally.  It is also the root node of the DOM.

console.log(document.nodeType);

The document object implements the Document, HTMLDocument, node, and EventTarget interfaces.

Some of the properties that we’ve already discussed from the node interface have the following values.

  • nodeType: 9
  • nodeName: “#document”
  • nodeValue: null
  • parentNode: null
  • ownerDocument: null
  • child nodes may have the following types:
    • DocumentType
    • Element (html)
    • ProcessingInstructions
    • Comment

Special Node References

Though accessible through the document object’s childNodes list, the document object has two properties that give direct access to the <html> element and the <body> element.

var html = document.documentElement;   // html element
var body = document.body;              // body element

document.title

var title = document.title;         // Get title
document.title = “New Title”;       // Set title

document.URL (read only)

The document.URL property holds the URL of the current page.

document.domain 

The document.domain property holds the domain portion of the URL.  It can be retrieved and set in some instances.  For example, if the domain is sub.domain.com, the domain might be able to be set to domain.com.

document.referrer (read only)

The document.referrer property may contains the URL of page that linked to the current page.  it may also have the same value as document.URL.

Special Collections

The document object also has properties that contain HTMLCollection objects that provide quick access to various sets of nodes in the DOM.

The HTMLCollection Object

The HTMLCollection object extends NodeList.  We can retrieve an individual element node within the collection using any of the following methods:

  1. Use the HTMLCollection function namedItem(id)
  2. Use the HTMLCollection function item(index)
  3. Use bracket notation with the element’s id
  4. Use bracket notation with a list index number

For example, suppose the web page contains the following anchor element.

<a id="home" href="http://www.n0code.net">n0code.net</a>

Below we use each of the methods listed above to retrieve the <a> element that has its id attribute set to “home”.

var links = document.links;

var link1 = links.namedItem("home");
var link2 = links.item(0);
var link3 = links["home"];
var link4 = links[0];

console.log(link1.firstChild.nodeValue);  // "n0code.net"
console.log(link2.firstChild.nodeValue);  // "n0code.net"
console.log(link3.firstChild.nodeValue);  // "n0code.net"
console.log(link4.firstChild.nodeValue);  // "n0code.net"