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"