The Document Object in JavaScript

Table of content:

What is the document object

The document object is an object created automatically by the browser for each new HTML page that is viewed and you can access a number of properties and methods that can affect the document which are very useful when writing scripts.

The Document Object Model (DOM)

The Document Object Model (DOM) allows JavaScript to access the structure of the document in the browser. Each HTML document is made of structured nodes. For example the body tag is a node and any element within the body will be a child node of the body element. Of course, each child node can have its own nodes too. Example:


<body>
<h1>Nodes and child nodes</h1>
<img src="myimage.jpg" alt="My Image" />
</body>

The body element is a node. It has two child nodes: the h1 element and the img element. The h1 contains a text node as its child node. The img element contains two attribute nodes:
src="myimage.jpg" and alt="My Image".

Accessing the DOM allows you to create more dynamic pages. You can also create elements and nodes using certain JavaScript methods of the document object.

Properties of the document object

The table below lists the properties of the document object with a short description of each property. Not all properties are cross-browser and some of them have been deprecated.

Property Description
activeElement Returns a string holding the value of the active element in the document.
alinkColor Returns the hexadecimal value of the active link color of the document.
anchors An array of all the named anchors in the document.
async Tells the browser whether to load a document with an asynchronous request or a synchronous request.
applets An array of all the Java applets in a document.
bgColor Returns the hexadecimal value of the background color of the document.
body Returns the body or the frameset element of the document.
characterSet Returns a string value that represents the character set used to encode the document.
charset Returns a string value that represents the character set used to encode the document.
childNodes An array of all the child nodes of the document.
compatMode Returns the string “BackCompat” if the document is rendered in Quirks mode or the string “CSS1Compat” if the document is rendered in Strict Mode.
contentType Returns a string for the Content-Type from the MIME header of the document.
cookie Used to set JavaScript cookies in a document.
defaultCharset Returns a string value that represents the default character set used to encode the document.
defaultView References the window object for the document.
designMode Returns a string value that provides information on whether or not the document can be edited.
dir Returns a string value that represents the reading direction of the document.
doctype Returns the doctype declaration associated with the document.
documentElement Returns a string that represents the root node of the document.
documentURIObject Returns an object that represents the URI of the document (available only to privilege JavaScript code).
domain Returns the domain name of the server for the document.
embeds An array of all the embed tags in the document.
expando Returns a boolean value based on whether or not arbitrary variables can be created within the document.
fgColor Returns the hexadecimal value of the default text color of the document.
fileCreatedDate Returns the date the document was created.
fileModifiedDate Returns the date the document was last modified.
formName Creates a new property with each named form placed in the document.
forms An array of all form tags in a document.
frames An array of all the frames used in a document.
height Returns the height in pixels of the body element of the document.
images Returns an array of all the image tags in the document.
implementation Returns a string value representing the implementation object of the document.
inputEncoding Returns a string that represents the document’s encoding.
lastModified Returns the date of the last modification of the document.
layers An array of all the layer tags on the page (Netscape Navigator 4 only).
all Allows access of all the objects on a page.
linkColor Returns the hexadecimal value of the default link color for the document.
links An array of all the link tags in the document.
location Returns the URI of the document.
namespaces An array of all the namespaces in the document.
parentWindow Returns a referance to the parent window (the parent window’s document object).
plugins An array of all the plugins used in the document.
protocol Returns the protocol portion of the web address (URL) of the document.
readyState Returns a string value that represents the current state of the document.
referrer Returns the URL of the document that referred the viewer to the current document.
scripts An array of all the script tags used in the document.
styleSheets An array of all the style sheets used in the document.
tags Sets the style of an HTML tag in the document.
title Returns the text used inside the title tag of the document.
uniqueID Returns a string value that represents a unique ID given to the document.
URL Returns the URL of the current document.
URLUnencoded Returns the URL of the document without any encoding.
vlinkColor Returns the hexadecimal value of the visited link color for the document.
width Returns the width, in pixels, of the body element of the document.

The color property

The alinkColor, bgColor, fgColor, linkColor, and vlinkColor properties were often used to obtain or change the color
of html elements on the page. They now have to be set with CSS or changed using style property.

The anchor property (Array)

The anchor property is actually an array set by the browser for all the named anchors in the document. On this page all the “Back to top” links are anchor links. In JavaScript, the length property allows you to find how many named anchors there are on the page.


<body>
<h1>The anchor property</h1>

<a name="anchor1"></a>
<h2>Honda motorcycles</h2>
<p>This paragraph talks about Honda motorbikes.</p>

<a name="anchor2"></a>
<h2>Yamaha motorcycles</h2>
<p>This paragraph talks about Yamaha motorbikes.</p>

<a name="anchor3"></a>
<h2>Suzuki motorcycles</h2>
<p>This paragraph talks about Suzuki motorbikes.</p>

<script type="text/javascript" >
document.write("There are "+document.anchors.length+" named anchors on this page.");
</script>
</body>

The cookie property

The cookie property is used to store information for the viewer. A cookie is a small text file saved to viewer’s computer for a certain amount of time. With the use of cookies a site can remember and retrieve information for viewer (the content of a shopping cart, settings, etc).
Example:


document.cookie = string;

You have to replace the word string with the text string that contains information you want to use. Example:


document.cookie = "site = homepage"

The dir property

The dir property returns a string value that represents the reading direction of the document. This value can be ltr (left to right) or rtl (right to left). This property is very useful for displaying pages written in languages that are read from right to left.


<body>

<form>
<input type="button" value="Change It" id="changer" onclick="switch_sides();" />
</form>

<script type="text/javascript" >
var MyButton = document.getElementById("changer");
MyButton.onclick = function() {
document.dir = (document.dir!="ltr") ? "ltr" : "rtl";
}
</script>

</body>

The domain property

The domain property holds the name of the domain name that saved the page to the viewer. It is everything after http:// and before any other slash.


document.write("You are at "+document.domain+" domain!");

The output is “You are at dandumitrache.com domain!”. Be aware that if you use this property locally, not on a real server, the output might be an empty string.

The formname property

The formname property is actually not a property itself but the property is the name of the form you create.


<body>

<form name="TheForm">
<input type="button" name="MyButton" value="Click if you are not afraid" />
</form>

</body>

The code creates a document.TheForm property from the name=”TheForm” attribute from the form tag which allows you to access the form elements within the form. Example:


<body>

<form name="TheForm">
<input type="button" name="MyButton" value="Click if you are not afraid"
onclick="document.TheForm.MyButton.value = 'Wow, you clicked, thanks!';"/>
</form>

</body>

The code accessed the form element first then the button within the form then the value of the button. Now, when you click the button its value is changed.

Note:
It is recommended to access form elements by assigning an id to the form and using document.getElementById() method.

The forms property (Array)

The forms property is an array that has an entry for each form on a webpage. Another alternative would be to use lenght property as document.forms.lenght to find out how many forms are on the page.

The images property (Array)

The images property is an array that has an entry for each image on a webpage. Another alternative would be to use lenght property as document.images.lenght to find out how many images are on the page.

Using this property you can detect what browser supprts the Image Object in JavaScript. This is useful if you want to preload an image which is a very good idea when using image rollover scripts or you want to place in viewer’s cache file a picture to use on oher pages on the website, to make it load quiker.


if (document.images) {
JavaScript code here
}

All is needed between parentheses is document.images. If this property exists it returns true and the code inside the block is executed. If the property doesn’t exist then the block is ignored.

If you want to preload an image then you have to create a new instance of the JavaScript Image object.


var NameOfTheVariable = new Image(width, height);

Of course you have to replace NameOfTheVariable with a meaningful name, and width and height with their correspondent values in pixels. The width and height parameters are optional.

The last thing you need to add is the source of the image so the browser knows where to take the image from. To do that you use the src property.


var HondaImage = new Image();
HondaImage.src = "MyHonga.jpg";

Note:
Preloading of an image is usually done in the head section of a document. If you want to preload more than an image then you have to create an instance of the image object for each image you want to preload.


if (document.images) {
var HondaImage = new Image(); //This is a new instance of the Image object
HondaImage.src = "MyHonga.jpg"; //The value of src property

/*Preload more than one image by creating
an instance of the Image object for each image you want
to preload. */

var YamahaImage = new Image();
YamahaImage.src = "MyYamaha.jpg";

var SuzukiImage = new Image();
SuzukiImage.src = "MySuzuki.jpg";
}

The lastModified property

The lastModified property holds the value of the date and time the document was last modified. Example:


<h1>Updated page</h1>

<script>
document.write("The page was updated on "+document.lastModified);
</script>

The links property (Array)

The links property is an array that holds the value of each link on the page. You can find out how many links are on a page by using document.links.lenght property.

The referer property

The referer property holds the value of the URL the viewer was on before arriving at your page. This is very useful information but the viewer can come to your page from a bookmark which will give nothing (undefined) as a value.


window.alert ("You come from "+document.referer);

The title property

The title property holds the value (string) of the title of the HTML document. The title is set within the title tags in the head section of the document.


<head>
<title>Honda Bikes</title>
</head>
<body>

<script>
document.write("<h1>" + document.title + "</h1>");
</script>

<p>Honda bikes are among the best in the world.</p>

</body>

This is useful when you want to display the title of the document in another place than in the top bar of the window.

The URL property

The URL property holds the value of the full URL of the current document. This information can be useful if you print it at the bottom of your page to be shown to everyone who prints out your page.


document.write(document.URL);

The URLUnencoded property

The URLUnencoded property returns the URL without any encoding. If there is a space within the link it won’t be replaced by %20 for example.

Note:
At the moment of writing only Internet Explorer supports URLUnencoded property.

The Methods of the Document Object

The methods of the document object allow you to do things that can’t be otherwise done. Below is a table containing the methods of the document object and a short description of each method.

Method Description
attachEvent() Attaches a function to an event (IE only).
createAttribute() Creates an attribute with a name that is sent to it as a parameter.
createAttributeNS() Creates a new attribute in a particular namespace.
createCDATASection() Creates a new CDATA section.
createComment() Creates a comment with a value that is sent to it as a parameter.
createDocumentFragment() Creates a new document fragment.
createElement() Creates an element of the type sent to it as a parameter.
createElementNS() Creates an element in a particular URI and a particular type sent to it as parameters.
createEntityReference() Creates a new entity reference.
createEvent() Creates an event.
createEventObject() Creates an event object for the purpose of passing event information.
createNodeIterator() Creates a node iterator object.
createNSResolver() Creates a namespace resolver.
createProcessingInstruction() Creates a processiong instruction.
createRange() Creates a range object.
createStyleSheet() Creates a style sheet for the document to use (IE only).
createTextNode() Creates a text string from the value sent to it as a parameter.
createTreeWalker() Creates a treewalker object.
detachEvent() Detaches a function from an event (IE only).
elementFromPoint() Returns the element object that appears at the location that is sent
to it in two parameter values (pixels from left and pixels from top).
evaluate() Returns a result based on the parameters sent to it.
execCommand() Executes a command on the document when the document is in design mode.
getElementById() Returns a reference to the object with the ID attribute that is sent to it as a parameter.
getElementByClassName() Returns references to the elements with the class name that is sent to it as a parameter.
getElementByName() Returns references to the objects with the name attribute that is sent to it as parameter.
getElementByTagName() Returns references to the elements with the tag name that is sent to it as a parameter.
getElementByTagNameNS() Returns references to the elements with the tag name and namespace that is sent to it as a parameter.
getSelection() Returns the value of a string of selected text in the document.
hasFocus() Returns a Boolean value based on whether or not the document has focus.
load() Loads an XML document.
mergeAttributes() Copies attributes from an object.
open() Opens a new document that allows you to write its contents using write() or writeIn() statements.
close() Closes a new document that has been opened with the open() method.
queryCommandEnable() Returns a Boolean value based on whether or not a command sent to it as a parameter can be executed.
queryCommandIndeterm() Returns a Boolean value based on whether or not a command sent to it as a parameter is in the indeterminate state.
queryCommandState() Returns a Boolean value based on whether or not a command sent to it as a parameter has executed.
queryCommandSupported() Returns a Boolean value based on whether or not a command sent to it as a parameter is supported.
queryCommandValue() Returns the current value of the document for the command that is sent to it as a parameter.
recalc() Recalculates the dynamic properties in a document.
releaseCapture() Releases the mouse capture from the document.
setActive() Sets an object as active but doesn’t give it focus.
write() Allows you to write a string of text into an HTML document.
writeln() Allows you to write a string of text into an HTML document but ends the line with a JavaScript newline character.

getElementById()

The getElementById() method allows you to access an element by the value of its id attribute. Example:


<div id="MyDiv">
Content goes here.
</div>

<script>
var FirstDiv = getElementById("MyDiv");
</script>

You can make you of an event that occurs on this element and script a reaction to the event.

getElementByClassName()

This method allows you to get an array with all the elements of the document that have the specified CSS class name sent as a parameter. For example, if you have a class named FirstClass then you can obtain all the elements with this class name by using the following code:


var CSSClass = getElementByClassName("FirstClass");

getElementByTagName()

This method allows you to get an array with all the elements of the document that have the specified tag name sent as a parameter. For example, to obtain all the image elements in the document you could use the following code:


var AllImages = getElementByTagName("img");

The open() and close() methods

The open() method allows you to create a new document and write its content entirely using document.write() or document.writeIn() statements. To finish the new page you have to use document.close(). Example:


<body>

<h1>Enter your name below</h1>

<form id="NewPage" onsubmit="CreateNewPage();">
You Name:
<input type="text" id="YourName" /><br />
<input type="submit" value="Submit" />
</form>

<script>
function CreateNewPage() {
var TheName = document.getElementById("YourName").value;

document.open();
document.write("<h2>Welcome!</h2>");
document.write("Hello "+TheName+" and welcome to my page!");
document.close();
}
</script>

</body>

In my example I created a form with an input box where the user can type in his name. The form and the input box are given each an id. Below I created a submit button which on submit (onsubmit=”CreateNewPage();) triggers the JavaScript function CreateNewPage().

Then I created the function CreateNewPage() which grabs the content of the text box and assigns it to a variable called TheName.

The document.open(); opens the new customized page in the browser. The two document.write() statements write the text on the page. The document.close() closes the new page.

The open() and close() methods can be useful when you want to create customized pages on-the-fly based on variables like name, favorite things, etc.

The write() method

The document.write() method is used to write a string value to the page. Example:


document.write("Hello world!");

The writeln() method

The writeln() method works just like the document.write() method but adds a JavaScript newline character (\n) at the end of the statement.

Note:
JavaScript newline character places a new line ONLY in the source code when usin document.write() method to make it easier to read. However, it can be use to create new lines in display elements such as alert boxes, prompts, etc.


document.write("Hello world! \n Is everything okay?");

Since the document.writeln() method adds a new line character at the end of the statement we could rewrite the code as follow:


document.writeln("Hello world!");
document.writeln("Is everything okay?");

Although the code is on two lines, the appearance in the browser is the same.

Creation methods

There are methods of the document object (createElement(), createAttribute(), and create TextNode()) that allow you to create various elements or nodes on the page using JavaScript.

However, the new content must be appended as a child of an existing node in the DOM. Below you have the table of the DOM node properties.

Property Description
attributes An array of all the attributes in the specified node; the name and the value properties of this property
can be used to access the attribute name or attribute value for each member of the array.
childNodes An array of all the child nodes of the specified node.
className Reurns the value of the class attribute of the specified node.
clientHeight Returns the height in pixels of the specified node.
clientWidth Returns the width in pixels of the specified node.
dir Returns the value of the direction of the text in the specified node (ltr or rtl).
firstChild Returns the first child node of the cpecified node.
id Returns the value of the id of the specified node
innerHTML Returns the HTML code within the specified code such as all of the HTML code within a div element.
lang Returns the language value of the specified node.
lastChild Returns the last child node of the specified node.
nextSibling Returns the node following the specified node.
nodeName Returns the name of the specified node (div for a div element for example).
nodeType Returns the type of the specified node.
nodeValue Returns the value of the specified node (the text within a div element or the
value of an attribute for example).
offsetHeight Returns the offset height of the specified node.
offsetWidth Returns the offset width of the specified node.
ownerDocument Returns the document object that contains the specified node.
parentNode Returns the parent node of the specified node.
previousSibling Returns the node before thespecified node.
scrollLeft Returns the difference between the left edge and the left edge in view of the specified document.
scrollTop Returns the difference between the top edge and the top edge in view of the specified document.
scrollHeight Returns the entire height (including anything hidden and viewable via scroll bar) of the specified node.
scroolWidth Returns the entire width (including anything hidden and viewable via scroll bar) of the specified node.
style Returns the style object of the specified node.
tabIndex Returns the tab index of the specified node.
tagName Returns the tag name (in uppercase) of the specified node.
title Returns the value of the title attribute of the specified node.

The “specified node” mentioned continuously in the table works almost like any other element you worked with. Let’s consider the following HTML code:


<body>
<div id="div1" title="DanD">
This page is about me!
</div>
</body>

In order to get the value of the title attribute of the div element, you could use document.getElementById() to grab the div element by its id of div1. This would be the specified node for the DOM node title property. To access the title property of the element node you can use the following code:


<body>

<div id="div1" title="DanD">
This page is about me!
</div>

<script type="text/javascript" >
var MeDiv = document.getElementById("div1");
var MeTitle = MeDiv.title;
document.write("The title of the div is "+MeTitle);
</script>

</body>

The MeDiv.title property returns a string value “DanD” which is the value of the div element node’s title attribute.

DOM Node Methods

Method Description
addEventListener() Adds an event listener to the specified node to run a function on the event sent to it as a parameter.
appendChild() Appends a node as the last child of the specified node.
attachEvent() Attaches an event to the specified node to run a function on the event sent to it as a parameter.
blur() Removes focus from the specified node.
click() Executes the click event on the specified node.
cloneNode() Creates a clone of the specified node.
detachEvent() Detaches an event from the specified node.
dispatchEvent() Executes an event on the specified node.
focus() Gives focus to the specified node.
getAttribute() Returns the value of the attribute name sent to it as a parameter on the specified node.
getAttributeNS() Returns the value of the attribute name and namespace sent to it as a parameter on the specified node.
getAttributeNode() Returns the attribute node of the attribute name sent to it as a parameter on the specified node.
getAttributeNodeNS() Returns the attribute node of the attribute name and namespace sent to it as a parameter on the specified node.
getElementByTagName() An array of all the child element nodes with the tag name sent to it as parameter in the specified node.
getElementByTagNameNS() An array of all the child element nodes with the tag name and namespace sent to it as parameter in the specified node.
hasAttribute() Returns true if the attribute name sent to it exists on the specified node, or false if not.
hasAttributeNS() Returns true if the attribute name and namespace sent to it exists on the specified node, or false if not.
hasAttributes() Returns true if the specified node hasany attribute nodes defined, or false if not.
hasChildNodes() Returns true if the specified node has any child nodes, or false if not.
insertBefore() Inserts a node sent to it as parameter before the node sent to it as a second parameter inside the specified node.
normalize() Normalizes the specified node.
removeAttribute() Removes the attribute node for the attribute name sent to it as parameter from the specified node.
removeAttributeNode() Removes the attribute node for the attribute node object referance sent to it as parameter from the specified node.
removeAttributeNS() Removes the attribute node for the attribute name sent to it as parameter with the namespace
sent to it as parameter from the specified node.
removeChild() Removes the child node sent to it as parameter from the specified node.
removeEventListener() Removes an event listener from the specified node.
replaceChild() Replaces the child node sent to it as the second parameter with the child node sent to it
as the first parameter in the specified node.
scrollIntoView() Scrolls the specified node into view in the browser window.
setAttribute() Sets an attribute node’s name (first parameter) and value (second parameter) for the specified node.
setAttributeNode() Sets an attribute node as the attribute node object sent to it as parameter for the speified node.
setAttributeNodeNS() Sets an attribute node as the attribute node object sent to it as parameter
with the namespace sent to it as parameter for the speified node.
setAttributeNS() Sets an attribute node’s namespace (first parameter), name (second parameter),
and value (third parameter) for the specified node.

Adding new node to a document

To make the creation method of the document object useful by adding the created node to the document, the DOM node method, such as appendChild() or insertBefore(), is needed to add the new node to the document. Example:


<div id="div1" title="DanD">
This page is about me!
</div>

The above code has a div element with a child text node (and attribute nodes). Let’s say that you want to create another div element as the last child node of the div1 element node, then you can use a combination of document.createElement(), document.createTextNode(), and the DOM node method appendChild().

Step 1


var MeDiv = document.getElementById("div1");

This grabs the div1 element by its id.

Step 2


var InnerDiv = document.createElement("div");

This creates a new element node.

Step 3


var InnerDivText = document.createTextNode("Read more about me!");

This creates the text node for the InnerDiv node by using the document.createTextNode() method.

Step 4


InnerDiv.appendChild(InnerDivText);

This adds the text node InnerDivText as a child of the new InnerDiv using appendChild() DOM node method.

Step 5


MeDiv.appendChild(InnerDiv);

This adds the InnerDiv node to the document structure as the last child element of the MeDiv node.

The document structure would look like is shown below.


<div id="div1" title="DanD">
This page is about me!
<div>
Read more about me!
</div>
</div>

When you create complex scripts these properties and methods of the DOM nodes will be very useful.

Creating Dynamic Scripts

Since JavaScript gives you access to all of the elements of a document, you can access and modify their style attribute (typically set by CSS) using the style DOM node property.

Styles in JavaScript

The style of a webpage is usually set with CSS (Cascade Style Sheet). In a CSS document you might have something like this:


<style>
#div_1 {
color: #000000;
background-color: #FFFFFF;
}
#div_2 {
border-style: solid;
border-width: 1px;
border-color: #000000;
}
</style>

This code gives you style attributes for two ids, div_1 and div_2, which means we have one div element with “id=div_1” and another div element with “id=div_2”.

JavaScript can access these divs using document.getElementById() method.


var d1 = document.getElementById("div_1");
var d2 = document.getElementById("div_2");

In order to modify the style of an element via JavaScript we have to use the style property.


d1.style.color = "#999999";

Note:
The CSS property background-color won’t work in the example above because JavaScript doesn’t allow hypens to be part onames. However, if you use backgroundColor instead of background-color then everything will work perfectly. The rule is: eliminate the hypen and capitalize the word that follows it.


d1.style.backgroundColor = "#00FF00";

Coding a dynamic script

The scripts you create can be alter as a result of user interactions or events.

Let’s say we want to change the background color of the div_1 and the border of the div_2 when user’s mouse moves over the div with the id div_1.


<body>

<div id="div_1">
Cotent of the first div.
</div>
<div id="div_2">
Cotent of the second div.
</div>

<script>
var d1 = document.getElementById("div_1");
var d2 = document.getElementById("div_2");
d1.onmouseover = function () {
d1.style.backgroundColor = "#00FF00";
d2.style.borderWidth = "5px";
}
d1.onmouseout = function () {
d1.style.backgroundColor = "#FFFFFF";
d2.style.borderWidth = "1px";
}
</script>

</body>

Of course this is just an example but you can modify the entirety of the HTML code within a given element using the DOM node innerHTML property.

The innerHTML property

The innerHTML property allows you to change the code that is inside an HTML element.


<body>

<div id="div_1">
What is 3+2?
</div>

<div id="div_2">
<a href="answer.html" id="the_answer">Get the answer</a>
</div>

</body>

Let’s start off by setting up two divs with ids div_1 and div_2. div_1 contains a question and div_2 contains a link to the answer of the question. Now we want when someone clicks the link in the div_2, the text displayed in div_1 to change.


<body>

<div id="div_1">
What is 3+2?
</div>

<div id="div_2">
<a href="answer.html" id="the_answer">Get the answer</a>
</div>

<script type="text/javascript">
var d1 = document.getElementById("div_1");
var the_link = document.getElementById("the_answer");

the_answer.onclick = function () {
d1.innerHTML = "Easy answer ... it's 5!";
return false;
}
</script>

</body>

Note:
The return false; statement is placed at the end in order to keep the link from being followed when clicked.

Leave a Reply