Return to Course Content Home

JavaScript DOM Objects

 

Recommended Reading

The JavaScript Tutorial at https://www.w3schools.com/js/default.asp

Background

Perhaps one of the most powerful class of Objects in JavaScript are the Document Object Model(DOM) objects. These objects describe the browser, the page currently showing in the browser, and EVERY COMPONENT IN THAT PAGE. You can use JavaScript to modify an entire HTML document on the fly.

Before we get to the actual HTML page, there are several Objects that contain useful information about your Browser and Browser windows.

Window Object

This is the parent object in the JavaScript document structure. It represents your browser window or pop-up window, and can create pop-up windows as well. Window Objects are created every time a document has a <body> or <frameset> tag.

There are several useful properties for a Window object. Note that for your primary window, you don't have to preface a property with the window object (or you can preface it with window, which I recommend), but if you make a pop-up window, you use that window id.

For example, the "closed" property tests if a window is closed or not. If you want to see if the primary Window is closed, you would type

if (closed) {
 // do something
}
  
  or you could use...
if (window.closed) {
  // do something
}

But if you made a pop-up window, you would do something like this

popup=window.open('','','width=100, height=100');
if (popup.closed) {
  // do something
}

So, given the above, some of the useful properties are:

Property
Value
closed Tests if a window (main or popup) is closed
defaultStatus Gets or sets the default text in the statusbar of the window (this may not work in all browsers (Firefox 2.0 is one of them))
document Actually a complete JavaScript Object. The HTML document contained in the Window (see the next module)
history Allows you to direct the browser to go to a page in the browser history list (you can't read it, you can just go to it)
location Actually a complete JavaScript Object. Contains information about the current URL (see below)
name The name of the window
opener Reference to the parent of this window
parent Reference to the parent of this window
personalbar Gets or sets whether the browser's personal bar is available
status Sets the text in the statusbar of the window. (this may not work in all browsers (Firefox 2.0 is one of them))
top Returns the topmost ancestor window

Some of the useful Window Object methods are

Method
Function
alert() Makes a dialog window with a message and an OK button
blur() Removes focus from current window
setInterval(fn(), millis) Calls a function "fn()"or evaluates an expression every "millis" milliseconds. To stop this behavior, use clearInterval()
setTimeout(fn(), millis) Calls a function "fn()"or evaluates an expression after "millis" milliseconds. To stop this behavior, use clearTimeoutl()
close() Close this window
confirm(msg) Displays a small pop-up dialog with an OK and Cancel button. The confirm() method returns true if OK is selected, false for cancel.
moveBy(x,y) Moves a window by the given pixels
moveTo(x,y) Moves a window to the given position
resizeBy(x,y) Resizes a window by the adding to the existing size
resizeTo(x,y) Resizes a window to the given pixels
scrollBy(x,y) Scrolls by the pixels given
scrollTo(x,y) Scrolls to the given pixels
open(url, name, attributes, replace)

Creates a new window.

  • URL: the URL to be loaded, if left blank an empty window is created
  • name: the name of the window
  • attributes: Allows you to configure window use yes/no/1/0 parameters on values such as:resizable, titlebar, copyhistory, fullscreen. You can also set width, height, top and left values for the window
    e.g.(window.open("https://java.sun.com");
    e.g.(window.open("https://java.sun.com", "java", resizeable=no, height=100, width=100, top=50, left=50"
  • replace: (optional) does the URL create a new entry or replaces the current history
print() Prints the contents of the window
prompt(msg, default_text)) Makes a dialog with the "msg" as a message asking for user input. The optional "default_text" is the default text for the user input field

Even more interesting, once you make a popup window, you can write HTML on the fly to it using JavaScript

popup=window.open('','','width=100, height=100');
popup.document.write("<html>"); popup.document.write("<head>"); popup.document.write("<title>"); popup.document.write("Dynamic Window Content>"); popup.document.write("</title>"); popup.document.write("</head>"); popup.document.write("<body>"); popup.document.write("Hello World!"); popup.document.write("</body>"); popup.document.write("</html>"); popup.document.close();

The above code will open a window, then populate the empty window with HTML that will render a "Hello World" in the window.

Navigator Object

The Navigator object, like the Window object isn't really a DOM object. It is, in fact, a standalone JavaScript object that provides information about your browser. It is typically used to detect whether you are using IE, Firefox, or some other browser so that you can "adapt" to that browser's quirks.

There are several properties that you can get from the Navigator object, but be careful, they may not be what you expect. For example, getting appName() when running FireFox v2.0 returns "Netscape".

Screen Object

Like some of the other objects already listed, the Screen object is actually a standalone JavaScript object that provides information about a users screen. I won't list all of the attributes possible, just the more commonly used set.

Property
Value
availHeight The height of the display screen (less the taskbar)
availWidth The width of the display screen (less the taskbar)
colorDepth Number of bits in the color definition used by the screen
height The height of the display screen
width The width of the display screen

 

History Object

The History object sounds like it has more features than it really does. Not, you can't get a Users browsing history. What you can do is cause it to go forward, back, or go to a specific page.

Property
value
length The number of items in the browser history list

.There are three methods that can be used with the History object.

Method
Function
back() Loads the previous URL
next() Loads the next URL (if available)
go() Either go to a specific URL, or increment/decrement the index of the history list. (e.g. go(-2) goes back two items in the history list

 

Location Object

The Location Object lets you view/modify the current URL being shown in the browser. There are several properties that let you break apart the URL into useful information, and there are three methods that allow you to load or reload the document being shown.

Property
value
hash Sets/Gets the "anchor" part of the URL
host Sets/Gets the hostname and port part of the URL
hostname Sets/Gets the hostname part of the URL (no port number)
href Returns the complete, current URL
pathname Sets/Gets the current path of the URL
port Sets/Gets the port of the URL
protocol Sets/Gets the protocol of the URL (http, file, etc)
search Sets/Gets the part of the URL after the ? symbol

There are three methods that can be used with the Location object.

Method
Function
assign(URL) Loads a URL
reload() Reloads the current URL
replace(URL) Loads a URL

The Document Object Model (DOM)

The DOM breaks down your HTM document into the following structure

Let's look at a simple HTML document, and break it down into the above nodes and see how we access content.

<html xmlns="https://www.w3.org/1999/xhtml">
<head> <script type="text/javascript"> function changeStuff() document.getElementById("button1").value="You Did It!"; document.images.duke.src="Images/duke_wave.gif" document.body.style.backgroundColor="#0000AA"; document.getElementById("myText").style.color="white"; document.getElementById("theTitle").style.color="white"; document.getElementById("myText").innerHTML="Ouch!"; } </script> <title>Untitled Document</title> </head>
 <body bgColor="#FFFFFF">
   <h2 id="theTitle">Hello World Example</h2>
   <p id="myText">Hello World!</p>
   <input type="button" id="button1" value="Press Me!" onClick="changeStuff()">
   <img src="Images/duke_nowave.gif" name="duke" id="duke">
   </body>
</html>
 

Click on the button to bring up a new window that illustrates the above code.

The parent node of the document is the <html> node, it has two children, <head> and <body>. The <p>Hello World!</p> line is a text node. There are methods on the document object that let you get lists of elements by tag name.

If we want to access the elements of this HTML document, we first decide how we want to access them. For nodes with "id" tags, you can use the getElementById() method within document. The document object holds a list of all components by their id. The document object also has some "shortcuts" that allow you to quickly get at useful information

Notice how the <body> section has HTML tags that are given "id" and "name" tags that allow the JavaScript to easily access the elements within the changeStuff() function. <img> tags support the id attribute for the getElementById() method, or the name attribute to access the image directly.

By now you are saying to yourself, "Okay, this looks good, but how the heck do I know how to access all of these traits of the document object?" There is no great answer to this question, except experience and looking up examples while you are learning JavaScript.

The section below delineates different document traits that can be accessed. I don't expect you will remember them all (but what an awesome killer test this would make, right?). The recommended reading URL gives a lot of good examples of how to access the DOM.

Document Object Properties

The following table lists useful properties of the document object.

Property
Value
body Direct access to the <body> element
cookie Sets/Gets all cookies used by the document
domain Returns the web site host that hosts this document
lastModified Get the date/time this document was last modified
referrer Get the URL of the document that requested the current document to be loaded
title Get the title of the current document
URL Returns the URL of the current document

 

Document Object Lists

The following table lists the four lists that are built into the document object.

List
Description
anchors[] Returns a list that contains all anchor objects in the document
forms[] Returns a list that contains all form objects in the document
images[] Returns a list that contains all image objects in the document
links[] Returns a list that contains all link objects in the document

You can access elements in these lists by using their "name" attributes, as shown in the example in the previous section

document.images.duke referred to the duke image that is found in document.anchors[]. You can also access the images by indexing into the anchors[] array.

Document Object Methods

The following table shows the methods available to the document object.

Method
Function
close() Closes an output stream to a window. If you forget to use this when generating complete HTML document with write() calls, you'll notice the page still thinks it needs to load and the loading page icon in the browser never goes away.
getElementById(idString) Gets the object in the document with the given id="<id String>"
getElemenstByName(nameString) Gets the objects in the document with the given name="<name string>"
getElementsByTagName(tagString) Gets the objects in the document with the given attribute tag name (e.g <p> <h2>, ...
open() Opens a stream for writing to a document. This is opened automatically with a write() call.
write(String) Writes out the String to the document. No newline.
writeln(String) Writes out the String followed y a newline

Other objects found in a DOM document

There are many components that can be embedded in HTML pages. Some, like images, can already be accessed by using document.images. Others, like buttons, need to be accessed by their id's or name's. Once you have a reference to these objects, each one has its own set of Properties and Methods.

DOM Object
Common uses/methods/properties
Anchor This represents an <a> tag in HTML. You can pull out information about the url, target, text and id of the link.
Body This is the <body> of the document
Button You can get the id, name and type of the button and can set/get the text in the button (its "value")
Frame You can access borers, margins, id and the src URL of the frame
Image This allows you to have access to align, alt, border, height, hspace, id, name, src, vspace and width of an <img>
Input button You can simulate a mouse click with click(), or give/remove the focus. You can also access the id, name, type and value of the button.
Input Checkbox You can simulate a mouse click with click(), or give/remove the focus. You can also access the containing form, taborder, id, name, type and value of the checkbox. You can enable/disable the checkbox and can set whether it should be checked or not, of defaultChecked.
Input File Allows you to get the containing form, taborder, name, id, type and value of a FileUpload Object
Input Hidden Allows you to get the containing form, taborder, name, id, type and value of a Hidden Object
Input Password Allows you to get the containing form, taborder, name, id, type and value of a Password Object. The Object also supports a maxLength setting, whether it is disabled, and a defaultValue for the Object.
Input Radio Allows you to get the containing form, taborder, name, id, type and value of a Password Object. The Object also supports a defaultChecked and checked setting, whether it is disabled for the Radio Object.
Input Reset Allows yout to disable the input, get the containing form, the id and name of the component, the tabbing order, its type and value.
Input Submit Allows yout to disable the input, get the containing form, the id and name of the component, the tabbing order, its type and value.
Input Text Allows you to get the containing form, taborder, name, id, type and value of a Password Object. The Object also supports a maxLength setting, whether it is disabled, and a defaultValue for the Object.
Link Gets/Sets whether the link is disabled, and gets the type, id, name, and href
Meta Gets/Sets the value of the <meta> element and name the <meta> tag. Also gives the scheme used.
Option A Component in a dropdown list (Select) in a form. Lets you set the default selected value, disable the object, get the containing form and tabbing order, the id and name of the Option and the currently selected option along with the text value of the option and the value itself.
Select Get the array of all the options in the list, lets you disable the list, set if multiple selections are allowed, the id, name, size(visible rows), length and tabbing order of the list. This also lets you get the type of form element in the list. Methods exist to add/remove an option to a dropdown list and shift focus.
Style The Style object can be attached to any Object, and is covered more in the section below.
Table You can get lists of the rows and columns, set borders, cell spacing and padding. The id of the table. Methods exist for creating/deleting captions and inserting rows (not columns!)
TableCell A cell in a table. Properties for alignment, cellIndex, column spanning, id, innerHTML, rowSpan, width and vertical alignment.
TableRow Contains a list of cells in the row. Also has properties for alignment, id, and innerHTML. Methods exist to add/delete cells from a row.
Textarea Properties for the width and height of the textarea, defaultValue, containing form and tabbing order, id, name and value(text) in the textarea. Methods for shifting focus and selecting the text.

Style Object

The Style object represents a "style" description for most types of elements in a document. The Style object contains a large set of properties that can be modified to change the look of a component. Here we go...

Background Properties
background Allows you to set all background properties in a single statement, separated by spaces
backgroundAttachment If a background-image is fixed or scrolls with the page
backgroundColor The background-color of an element
backgroundImage The background-image of an element

backgroundPosition, backgroundPositionX, backgroundPositionY

Starting position of a background-image
backgroundRepeat does a background-image repeat or not
Border/Margin Properties
borderColor The color of all four borders.
border Allows you to set border properties in a single statement.
border<edge> where edge is Bottom, Left, Right or Top Allows you to set all border edge properties at once. (e.g. borderBottom....)
border<edge>Color where edge is Bottom, Left, Right or Top Sets the color of the edge border
border<edge>Style where edge is Bottom, Left, Right or Top Sets the color of the edge border
border<edge>Width where edge is Bottom, Left, Right or Top Sets the color of the edge border
borderWidth Sets the width of all four borders
margin

The margin of an element. Can be in % or pixels (px). You can have from 1 to 4 values, separated by spaces. Pattern is top, right, bottom, left margins.

e.g. document.getElementById("para1").style.margin="100px"
document.getElementById("para1").style.margin="10px 10px 5px 5px"

margin<edge> where edge is Bottom, Left, Right or Top sets individual margins.
outline sets outline properties in one statement
outlineColor Color of outline around an object
outlineStyle Style of the outline (none, dotted, dashed, double, groove, ridge, inset, outset, solid)
outlineWidth width of the outline
padding sets the padding properties in one statement
padding<edge> where edge is Bottom, Left, Right or Top extra space around an object.
Layout Properties
clear Ensures that left, right, both or no sides of text are clear of images or other floating elements
clip Allows you to specify a clipping mask for an element
cssFloat Sets where an image or text will float in another element
cursor Sets the cursor
display Controls how a element will be displayed on the page. Basically controls line breaks and block levels or table positioning.
width, height Sets the width height of an element
maxWidth, maxHeight, minWidth, minHeight Sets min/max values for an element
verticalAlign Sets the vertical alignment for an element
visibility Should the element be visible
List Properties
listStyle Lets you set the properties for displaying a list all at once
listStyleImage Lets you replace the default bullets/symbols for a list with an image
listStylePosition Lets you indent the marker and the text as opposed to just the text
listStyleType Large list with values for default list symbols (none, disc, circle, square, decimal, lower-roman, lower-alpha, upper-alpha, etc...)
Positioning Properties
bottom, left, right, top Lets you set how far this object should be from the edge of the document
zindex When items overlap, which is drawn first...
Printing Properties  
orphans Sets the minimum number of lines for a paragraph that must be at a bottom of a page
page Sets the page type to display an element
pageBreakAfter, pageBreakBefore, pageBreakInside Sets the page break behavior after, before, or inside an element. Values are always, auto, avoid, left, right