JavaScript Editor JavaScript Debugger     JavaScript Editor 



Team LiB
Previous Section Next Section

Document Object Model Redux

The DOM Level 1 attempts to standardize the JavaScript Document object to support the manipulation of arbitrary HTML elements and text objects while at the same time providing support for most commonly supported Document properties, collections, and methods. This backward support is often termed DOM Level 0 and is fairly consistent with what Netscape 3 supported except for JavaScript access to plug-ins. The Document properties supported by DOM Level 1 are presented in Table 13-3.

Table 13-3: DOM Level 1 Document Properties and Collections

Document Property or Collection

Description

anchors[]

Collection of the anchors defined by <a name="anchorname" >.

applets[]

The collection of Java applets in the page defined by the <applet> tag.

body

Reference to the object representing the <body> tag that contains the visible document.

cookie

A string holding the document's cookie value if any.

doctype

A reference to the DTD of the document.

documentElement

A reference to the root element of the document. In HTML this is the <html> tag.

domain

The security domain of the document.

forms[]

The <form> tags in the page.

images[]

The collection of images defined by <img>.

implementation

A reference to an object that can determine markup language feature support for the particular document.

links[]

The collection of the links specified by <a> and <area> tags in the page.

referrer

Holds the referring URL if any.

Title

The title of the document.

URL

A string holding the document's URL.

Notice in Table 13-3 how the DOM preserves many of the collections discussed up until now and only adds a few properties such as body, docType, and documentElement to the mix. The only thing missing seems to be lastModified; fortunately, browsers continue to support it.

Method-wise, traditionally the Document object only supported open(), close(), clear(), write(), and writeln(). The DOM Level 1 drops the clear() method, which never really had much use anyway. However, beyond the more staticially oriented write() methods, the DOM provides a variety of methods to dynamically create objects. It adds methods such as createComment(data), which creates an (X)HTML comment of the form <<!-- data -->>; createElement(tagName), which creates an (X)HTML of tagName; and createTextNode(data), which creates a text node containing the value of the paramater data. There are other DOM “create” methods, but they are not generally useful when working with HTML documents.

We also saw in Chapter 10 that the DOM adds three useful methods for retrieving a location in a document:

Once we retrieve an object, there are a variety of properties we can look at. For example, recall from Chapter 10 again that every DOM node including an (X)HTML element would have a variety of properties related to its position in the document tree, such as parentNode, childNodes, firstChild, lastChild, previousSibling, and nextSibling. There are also numerous methods such as insertBefore() to add nodes to the document whether they are HTML tags or text nodes. There are also properties to manipulate attributes and values, but this is often easier to perform directly, as we’ll demonstrate later.

Besides the DOM defined properties, understand that under HTML 4 and XHTML all elements have in common a core set of properties related to scripting, style sheets, and accessability (id, class, style, and title) as well as language usage (lang and dir). If you put all these together, you get the complete set of properties and methods common to any HTML element represented in JavaScript. Under the DOM, this object is called HTMLElement, and its properties and methods are summarized in Table 13-4.

Table 13-4: Common DOM Properties for HTMLElement

Common HTMLElement, Property, or Collection

Description

attributes[]

A collection of the attributes for the element, if any.

childNodes[]

A collection of the nodes (text nodes, elements, and so on) enclosed within the current HTML element.

className

The value of the class attribute.

Dir

The text direction of the enclosed text either LTR (left to right) or RTL (right to left) as set by the dir attribute.

firstChild

A reference to the first node directly enclosed within the current HTML element. This will be the same as element.childNodes[0]. Children, of course, can be any type, not just HTML elements.

Id

The text string set by the id attribute for the element.

lang

The language code for the element set by the lang attribute.

lastChild

A reference to the last child in the list of children nodes that are direct decendents of the current HTML element.

nodeName

The name of the HTML element, for example P. Same as tagName.

nodeValue

The value of the node. This property will always be null in the case of HTML elements.

nodeType

The numeric code for the node type. In the case of HTML elements, this will always be 1.

nextSibling

A reference to the next DOM node sibling of the current HTML element.

ownerDocument

A reference to the Document object containing the current element.

parentNode

A reference to the enclosing HTML element

previousSibling

A reference to the previous DOM node sibling of the current HTML element.

style

Access to the inline style specification for the current element. This is a DOM Level 2 property.

tagName

A reference to the name of the HTML element such as OL. This will be the same as nodeName in the case of element nodes.

Title

The text string holding the advisory text for the element set by the title attribute.

As mentioned in Chapter 10, under the DOM Level 1, all HTML elements also have a variety of useful methods. The more commonly used ones are presented in Table 13-5.

Table 13-5: Common DOM HTMLElement Methods

Method Name

Description

appendChild(newChild)

This method appends the node in newChild as the last child of the current element.

cloneNode(deep)

Makes a copy of the current HTML element. If the parameter deep is passed as true, the copy made includes all nodes enclosed within the current element.

getAttribute(name)

Returns the attribute name. Easier to reference directly via the attribute name when known. For example, if myP1 holds a paragraph, myP1.align would hold its align attribute value.

getElementsByTagName(tagName)

Returns a list of elements referenced by tagName that are contained within the current element.

hasChildNodes()

This method returns a Boolean value indicating if the current element has children (enclosed elements or text nodes).

insertBefore(newChild, refChild)

Inserts the node newChild into the list of children directly enclosed by the element just before the node referenced by refChild.

removeAttribute(name)

Removes the attribute named name. For example, myP1.removeAttribute("align") would delete the align attribute for a paragraph called myP1. Of course, it might just be easier to assign attributes back to their default values.

removeChild(oldChild)

Removes the node specified by oldChild.

replaceChild(newChild, oldChild)

Replaces the node oldChild with newChild.

setAttribute(name, value)

Returns the attribute name. Easier to reference directly via the attribute name itself when known. For example, if myP1 holds a paragraph, myP1.align would holds its align attribute value.

This section was only meant to remind readers of the basics of the DOM that was already covered in Chapter 10.

Accessing Specific HTML Element Properties

As mentioned in Chapter 10, the correlation between (X)HTML attribute names and DOM property names is nearly one to one. For example, the <<body>> tag would be represented by the DOM object HTMLBodyElement and would have the attributes previously discussed plus those related to its specific attributes, including aLink, background, bgColor, link, text, and vLink. Save for the JavaScript “camel-back” style of writing, these are just the attributes for the (X)HTML tag. While many tags like <<body>> have their own special attributes, there are many (X)HTML elements that only have a simple set of core attributes: id, class, style, and title and language attributes lang and dir. The DOM provides access to these as id, className, style, title, lang, and dir. Numerous (X)HTML elements as listed in Table 13-6 can be associated with the generic DOM object HTMLElement.

Table 13-6: (X)HTML Elements Associated with DOM HTMLElement

<sub>

<sup>

<span>

<bdo>

<tt>

<i>

<b>

<u>

<s>

<strike>

<big>

<small>

<em>

<strong>

<dfn>

<code>

<samp>

<kbd>

<var>

<cite>

<acronym>

<abbr>

<dd>

<dt>

<noframes>

<noscript>

<address>

<center>

All other (X)HTML tags inherit the same property/attribute relationship described in Table 13-6, but some tags have specific attributes beyond these. These tags and their associated DOM properties and, in some cases, methods are shown in Table 13-7. We have bolded the properties that vary from the attribute name because of the camel-back style for easy reference.

Table 13-7: (X)HTML Elements Associated with DOM Objects

(X)HTML Tag(s)

DOM Object

Properties

Methods

<html>

HTMLHtmlElement

Version

 

<head>

HTMLHeadElement

Profile

 

<link>

HTMLLinkElement

disabled, charset, href, hreflang, media, rel, rev, target, type

 

<title>

HTMLTitleElement

Text

 

<meta>

HTMLMetaElement

content, httpEquiv, name, scheme

 

<base>

HTMLBaseElement

href, target

 

<isindex>

HTMLIsIndexElement

form, prompt

 

<style>

HTMLStyleElement

disabled, media, type

 

<body>

HTMLBodyElement

aLink, background, bgColor,
link, text, vLink

 

<form>

HTMLFormElement

elements[], length, name,
acceptCharset, action,
enctype, method, target

submit(), reset()

<select>

HTMLSelectElement

type, selectedIndex, value, length,
form, options[], disabled, multiple,
name, size, tabIndex

add(), remove(), blur(), focus()

<optgroup>

HTMLOptGroupElement

disabled, label

 

<option>

HTMLOptionElement

form, defaultSelected, text, index,
disabled, label, selected, value

 

<input>

HTMLInputElement

defaultValue, defaultChecked, form,
accept, accessKey, align, alt, checked, disabled, maxLength, name, readOnly, size, src, tabIndex, type, useMap, value

blur(), focus(), select(), click()

<textarea>

HTMLTextAreaElement

defaultValue, form, accessKey, cols,
disabled, name, readOnly, rows,
tabIndex, type, value

blur(), focus(), select()

<button>

HTMLButtonElement

form, accessKey, disabled, name, tabIndex, type, value

 

<label>

HTMLLabelElement

form, accessKey, htmlFor

 

<fieldset>

HTMLFieldSetElement

form

 

<legend>

HTMLLegendElement

form, accessKey, align

 

<ul>

HTMLUListElement

compact, type

 

<ol>

HTMLOListElement

compact, start, type

 

<dl>

HTMLDListElement

compact

 

<dir>

HTMLDirectoryElement

compact

 

<menu>

HTMLMenuElement

compact

 

<li>

HTMLLIElement

type, value

 

<div>

HTMLDivElement

align

 

<p>

HTMLParagraphElement

align

 

<h1><h6>

HTMLHeadingElement

align

 

<q>

HTMLQuoteElement

cite

 

<pre>

HTMLPreElement

width

 

<br>

HTMLBRElement

clear

 

<basefont>

HTMLBaseFontElement

color, face, size

 

<font>

HTMLFontElement

color, face, size

 

<hr>

HTMLHRElement

align, noShade, size, width

 

<ins>, <del>

HTMLModElement

cite, dateTime

 

<a>

HTMLAnchorElement

accessKey, charset, coords, href,
hreflang, name, rel, rev, shape,
tabIndex, target, type

blur(), focus()

<img>

HTMLImageElement

lowSrc, name, align, alt, border, height, hspace, isMap, longDesc, src, useMap, vspace, width

 

<object>

HTMLObjectElement

form, code, align, archive, border, codeBase, codeType, data, declare, height, hspace, name, standby, tabIndex, type, useMap, vspace, width

 

<param>

HTMLParamElement

name, type, value, valueType

 

<applet>

HTMLAppletElement

align, alt, archive, code, codeBase, height, hspace, name, object, vspace, width

 

<map>

HTMLMapElement

areas, name

 

<area>

HTMLAreaElement

accessKey, alt, coords, href, noHref,
shape, tabIndex, target

 

<script>

HTMLScriptElement

text, htmlFor, event, charset, defer, src, type

 

<table>

HTMLTableElement

caption, tHead, tFoot, rows, tBodies, align, bgColor, border, cellPadding, cellSpacing, frame, rules, summary, width

createTHead(),
deleteTHead(),
createTFoot(),
deleteTFoot(),
createCaption(),
deleteCaption(),
insertRow(), deleteRow()

<caption>

HTMLTableCaptionElement

align

 

<col>

HTMLTableColElement

align, ch, chOff, span, vAlign, width

 

<thead>, <tfoot>, <tbody>

HTMLTableSectionElement

align, ch, chOff, vAlign, rows[]

insertRow(), deleteRow()

<tr>

HTMLTableRowElement

rowIndex, sectionRowIndex, cells[], align, bgColor, ch, chOff, vAlign

insertCell(), deleteCell()

<td>,<th>

HTMLTableCellElement

cellIndex, abbr, align, axis, bgColor, ch, chOff, colSpan, headers, height, noWrap, rowSpan, scope, vAlign, width

 

<frameset>

HTMLFrameSetElement

cols, rows

 

<frame>

HTMLFrameElement

frameBorder, longDesc, marginHeight, marginWidth, name, noResize, scrolling, src

 

<iframe>

HTMLIframeElement

align, frameBorder, height, longDesc, marginHeight, marginWidth, name, scrolling, src, width

 

Manipulating an (X)HTML element and its associated attributes is very straightforward once the element is accessed using a method like document.getElementById( ) as shown here:

<<p id="myP1">>Test Paragraph<</p>>
<<form action="#" method="get">>
<<input type="button" value="align left"
 onclick="document.getElementById('myP1').align='left';" />>
<<input type="button" value="align center"
 onclick="document.getElementById('myP1').align='center';" />>
<<input type="button" value="align right"
 onclick="document.getElementById('myP1').align='right';" />>
<</form>>

Adding (X)HTML elements is also straightforward using document.createElement() as shown in this next example, in which we follow the idea of the editor presented in Chapter 10. In this case, we allow the user to type in an arbitrary tag name and value and allow it to be added to the document. We apply a simple check to make sure that the user is not trying to add structural elements or add text content to an empty element, hinting at the type of logic one might start to employ to create a full-blown syntax-driven editor using the DOM.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Simple DOM Editor 0.2<</title>>
<<meta http-equiv="content-type" content="text/html; charset=utf-8" />>
<<script type="text/javascript">>
<<!--
var dangerousElements = 
{'html':true,'head':true,'body':true,'script':true,'style':true,'frameset':true,'
frame':true};
var emptyElements =
{'hr':true,'meta':true,'br':true,'area':true,'base':true,'basefont':true,'link':
true,'frame':true};
function addElement(theElement,theText)
{
 if (theElement in dangerousElements)
   {
       alert("Error: Element not allowed");
       return;
      }
 var newNode = document.createElement(theElement);
 if ((theText.length >> 0) && !(theElement in emptyElements))
  {
   var newText = document.createTextNode(theText);
   newNode.appendChild(newText);
  }
 else
   alert("Warning: Do not add text to an empty element");
 document.getElementById('insertHere').appendChild(newNode);
}
//-->>
<</script>>
<</head>>
<<body>>
<<div id="insertHere" style="width: 80%; border-style: dashed; border-width: 1px;">>
      &nbsp;
<</div>>
<<form action="#" method="get" name="theForm" id="theForm">>
 <<input type="text" value="i" name="theTag" id="theTag" />>
 <<input type="text" name="theText" id="theText" value="Testing 1..2..3.." />>
 <<input type="button" value="Create"
onclick="addElement(document.theForm.theTag.value,document.theForm.theText.value);
"  />>
<</form>>
<</body>>
<</html>>

It would be quite laborious and repetitious to demonstrate the creation of each and every tag from JavaScript. They all follow in the same spirit as the previous example. Interested readers can delve into Appendix B, which contains the complete listing of all (X)HTML-related properties from the DOM Level 1. However, before concluding this chapter, it is time to take a look at one (X)HTML element that continually causes developers trouble—the table.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Debugger     JavaScript Editor


©