Thursday, November 10, 2011

W3C DOM Implementation

The W3C DOM interface in Windows Internet Explorer allows authors to access different nodes of the document tree. A node is a reference to an element, an attribute, or a string of text. To implement the W3C DOM members, authors should understand the conceptual layout of the document tree and the relationship that nodes have with one another. While the W3C DOM provides a streamlined approach to completing tasks that are viable under the DHTML Object Model, it does not implement all of the DHTML Object Model members, particularly events. This section describes implementing the W3C DOM by navigating, creating, and manipulating nodes. It also provides a comparison between the W3C DOM and the DHTML Object Model.
Among the DHTML Methods, properties, and collections exposed as of Internet Explorer 5.5 are several DOM-specific members that represent the W3C DOM interface. The following tables outline these members.

Methods

addappendChildblurclear
clearclickcloneNodeclose
createCaptioncreateDocumentFragmentcreateElementcreateTextNode
createTFootcreateTHeaddeleteCaptiondeleteCell
deleteRowdeleteTFootdeleteTHeadfocus
getAttributegetAttributegetAttributegetElementById
getElementsByNamegetElementsByTagNamehasChildNodesinsertBefore
insertCellinsertRowitemitem
itemitemopenremove
removeAttributeremoveAttributeremoveChildreplaceChild
resetselectselectsetAttribute
setAttributesplitTextsubmitwrite
writeln

Properties

acceptCharsetaccessKeyactionalign
alignalignalignaLink
altbackgroundbackgroundbackground
bgColorborderborderborder
bordercaptioncaptioncellIndex
cellPaddingcellSpacingcharsetchecked
classNameclearclearcode
codeBasecodeTypecolorcolor
colscolscolscolSpan
contentcookiecoordsdata
datadefaultCheckeddefaultSelecteddefaultValue
deferdirdisableddisabled
documentElementdomainfacefirstChild
formframeframeBorderheight
heightheightheighthref
hrefhrefhrefhspace
htmlForhttpEquividindex
isMaplanglastChildlength
lengthlinklowsrcmarginHeight
marginWidthmaxLengthmediamethod
multiplenamenamename
namenextSiblingnodeNamenodeType
nodeValuenoHrefnoResizenoShade
noWrapobjectparentNodepreviousSibling
readOnlyreadOnlyreferrerrel
revrowIndexrowsrows
rowSpanrulesscrollingsectionRowIndex
selectableContentselectedselectedIndexshape
sizesizesizesize
spanspecifiedsrcsrc
srcsrcstarttabIndex
tagNametargettargettext
texttexttexttFoot
tHeadtitletypetype
typetypetypetype
typetypetypetype
typeURLuseMapvAlign
valuevaluevaluevalue
valuevLinkvspacewidth
widthwidthwidthwidth

Collections

anchorsappletsareasattributes
cellschildNodeselementsforms
imageslinksoptionsrows
rulestBodies
The following tables list the Document Object Model (DOM) Level 1 methods and properties that are supported by Internet Explorer 6 and later. As of Internet Explorer 6, all of the methods, properties, and collections defined in the Document Object Model (DOM) Level 1 specification are supported.

Methods

appendDatacreateAttributecreateCommentdeleteData
getAttributeNodegetNamedItemhasFeatureinsertData
namedItemnamedItemnamedItemnamedItem
normalizeremoveAttributeNoderemoveNamedItemreplaceData
setAttributeNodesetNamedItemsubstringData

Properties

abbracceptarchiveaxis
chchOffcitecompact
dateTimedeclaredoctypeheaders
hreflangimplementationlabellabel
longDescownerDocumentprofilescheme
scopestandbysummarytype
valuevalueTypeversionwidth

Navigating Nodes

Identifying a particular node is easy if a Web author knows the ID of the element. Finding an adjacent element, or locating an element in relation to another, can be more difficult. The W3C DOM exposes several properties and collections that identify a node, and the relationship a node has with other nodes.
The following HTML demonstrates a tree structure built from a ul element.
<UL ID="oParent">
   <LI>Node 1
   <LI ID="oNode">Node 2
      <UL>
         <LI>Child 1
         <LI ID="oChild2">Child 2
         <LI>Child 3
      </UL>
   <LI>Node 3
</UL>
Given a reference to a node in the list where the ID is oNode, the W3C DOM members can be used to identify the adjacent, parent, and child nodes. Since elements and text exist as nodes, they are accessible through the W3C DOM. The following code identifies the basic structure of the specified node, oNode.
<!-- oParent is the parent node of oNode. -->
<UL ID="oParent">
<!-- oNode is the childNode of oParent.-->
<LI ID="oNode">
<!-- Node 2 is a text node and is a child of oNode.-->
Node 2
</UL>
The ul and li elements are exposed in the DHTML Object Model. However, the text is only directly accessible as a node in the W3C DOM. Use the following diagram to identify the hierarchy of the list.
DOM Tree Sample
The first three li elements, labeled Node 1, Node 2, and Node 3, are the child nodes of the first ul element, oParent (Parent Node). The child nodes collection is exposed to oParent as childNodes, and contains Node 1, Node 2, and Node 3. As child nodes, these three li elements return oParent as the parent node through the parentNode property. Node 1, Node 2, and Node 3 are siblings and are exposed to each other through the previousSibling and nextSibling properties. Node 2 exposes a childNodes collection that contains three unlabeled li elements.
The following sample is an interactive tree that provides the same information as the previous diagram. It allows some experimentation with identifying the relationships of selected nodes and introduces tree manipulation.
Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dom/InteractiveTree.htm
The W3C DOM and DHTML Object Model provide a means to query a specified node to determine its location in the document hierarchy and its relationship to other nodes. Using the previous unordered list, querying the oNode object is compared between the W3C DOM and the DHTML Object Model as follows:
  • Parent. The parent of oNode has an ID of oParent in the HTML code.
    • DOM
      var oParent = oNode.parentNode
      
    • DHTML Object Model
      var oParent = oNode.parentElement
      
  • Previous Sibling. The nodes adjacent to oNode are labeled Node 1 and Node 3. The previous sibling is Node 1.
    • DOM
      var oPrevious = oNode.previousSibling
      
    • DHTML Object Model
      var oPrevious = fnGetSibling();
      function fnGetSibling(){
         var oParent=oNode.parentElement;
         var iLength=oParent.children.length;
         for(var i=0;i < iLength;i++){
            if(oParent.children[i]==oNode){
               return oParent.children[i - 1];
               break;
            }
         }
      }
      
  • Node Value. The node value of oNode is accessed through the W3C DOM using the nodeValue property, or the innerHTML or innerText property using the DHTML Object Model.
    • DOM
      oNode.childNodes[0].nodeValue="The new label";
      
    • DHTML Object Model
      oNode.innerHTML="The new label";
      
Notice the similarities and differences between querying the W3C DOM and the DHTML Object Model. First, the parentElement and parentNode properties return the same element for this sample. Second, finding the previous sibling using the DHTML Object Model is more tedious than simply using the previousSibling property exposed in the W3C DOM. And third, notice that the text is treated as a node in the W3C DOM and is accessible through the childNodes collection. An important distinction about a TextNode is that it cannot contain any child nodes.

Creating Nodes

Nodes are created using the createElement and createTextNode methods. Both methods are exposed only to the document object, and can be used in HTML documents, DHTML behaviors, and HTML Applications (HTAs). In the DHTML Object Model, elements are added to the document hierarchy by modifying the innerHTML and outerHTML property values, or by using methods explicit to particular elements, such as the insertRow and insertCell methods for the table element. With the createElement method, only the name of the element is needed.
Use the following syntax to create a new element.
// Create an element
var oElement = document.createElement(sElementName);
The createElement method is available in Internet Explorer 4.0, but only the area, img, and option elements can be created. As of Internet Explorer 5, all elements can be created stand-alone. In addition, read-only properties, such as id, are read-write for stand-alone elements before they are inserted into the document hierarchy. Some elements might require additional steps or rely on the existence of other elements. For example, the TYPE attribute of the input element defaults to text. So, to create a button control, the type property needs to be set to button, and the value property should be set to provide a label.
The following sample code highlights how a fieldSet, legend, and INPUT type=button control are created in script to build a short form. Notice that one function is designed to create and append the elements, and a reference to the new element is returned so additional elements can be appended as children.
function fnCreate(sElement,sData,sType,oNode){
   var oNewElement=document.createElement(sElement);
   if(sType){
      oNewElement.type=sType;
      oNewElement.value=sData;
   }
   if(sData){
      if(sElement.toLowerCase()!="input"){
         var oNewText=document.createTextNode(sData);
         oNewElement.appendChild(oNewText);
      }
   }
   if(oNode){
      oNode.appendChild(oNewElement);
   }
   else{
      oNewForm.appendChild(oNewElement);
   }
   return oNewElement;
}

var oNode=fnCreate("FIELDSET"); 
fnCreate("LEGEND","My Form","",oNode);
fnCreate("INPUT","Some Text","text",oNode);
fnCreate("INPUT","A button","button",oNode);
Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dom/CreateForm.htm
When creating and threading together nodes, it is important to use well-formed HTML to avoid creating an invalid tree. By creating and adding an invalid tree into the document hierarchy, unpredictable behavior can ensue. For the most part, Web authors need not be concerned. However, there are some elements, such as table, that warrant special discussion.
A well-formed HTML table consists of at least two nodes: table and tBody. In the DHTML Object Model, a table, with accompanying rows and cells, can be created using the innerHTML property, the insertRow and insertCell methods, and the rows and cells collections. While the tBody element is not explicitly added, it is created as a part of the table object model. For example, the following code generates a two-cell table using the DHTML Object Model.
var sTable="<TABLE ID='oTable1'></TABLE>"
document.body.innerHTML+=sTable;
oTable1.insertRow(oTable1.rows.length);
oTable1.insertRow(oTable1.rows.length);
oTable1.rows(0).insertCell(oTable1.rows(0).cells.length);
oTable1.rows(0).insertCell(oTable1.rows(0).cells.length);
oTable1.rows(0).cells(0).innerHTML="Cell 1";
oTable1.rows(0).cells(1).innerHTML="Cell 2";
The following HTML is the result of the previous code. Notice that the tBody element exists even though it was not added in script.
<TABLE ID="oTable">
<TBODY>
<TR><TD>Cell 1</TD><TD>Cell 2</TD></TR>
</TBODY>
</TABLE>
To create a well-formed table in the W3C DOM, the tBody element must be explicitly created and added to the tree. By not including the tBody element, the nodes comprising the entire table form an invalid tree and result in unpredictable behavior. The following script outlines the creation of a table using the W3C DOM, including the tBody element.
var oTable=document.createElement("TABLE");
var oTBody=document.createElement("TBODY");
var oRow=document.createElement("TR");
var oCell=document.createElement("TD");
var oCell2=oCell.cloneNode();
oRow.appendChild(oCell);
oRow.appendChild(oCell2);
oTable.appendChild(oTBody);
oTBody.appendChild(oRow);
document.body.appendChild(oTable);
oCell.innerHTML="Cell 1";
oCell2.innerHTML="Cell 2";

Manipulating Nodes

Once a node is created, and its relationship with other nodes is identified, it can be manipulated. A node can be updated without any knowledge of what nodes are adjacent to it, but it is a good idea to know what could be affected if a node is altered. For example, if a Web author wants to remove portions of a list, removing the topmost node and all its children might delete information that should have been preserved. In addition, removing only the topmost node of a list might cause additional problems later because the existing list items would still exist, without the ol or ul parent.
Some of the W3C DOM methods that allow authors to easily manipulate nodes are the cloneNode, removeNode, replaceNode, and swapNode methods. These methods provide copy, move, and delete functionality to the entire document tree. Understanding how a node interacts with other nodes helps keep a document clean and the client-side script stable. For example, consider the following list code.
<UL ID=oParent>
<LI>Item 1
<LI ID=oNode2>Item 2
<OL ID=oSubList>
<LI>Sub Item 1
<LI>Sub Item 2
<LI>Sub Item 3
</OL>
<LI>Item 3
</UL>
Manipulating nodes can be tricky because it is very easy to build invalid tree structures. For example, to copy one of the list items represented in the previous HTML and paste it at the bottom of the list, the new node should be appended to the parent, oParent, not the last list item. By appending the node to the last list item, the new node becomes a child of oParent, not a sibling to the other nodes. The converse is also true for appending children to each list item. If a new sublist is created and appended to oParent, it becomes a sibling to the other list items, not a child of a particular list item.
To create a new sublist of three items, one new ol element and three new li elements can be created and appended to the last list item. However, since this structure already exists, it can be copied with the cloneNode method. By passing true as a parameter to the method, the children are cloned as well. The following code demonstrates how the entire sublist is copied and appended to the last list item.
var oClone=oSubList.cloneNode(true);
oParent.childNodes[oParent.childNodes.length-1].appendChild(oClone);
The replaceNode and swapNode methods are used to exchange a node with one in the document hierarchy. The difference between these methods is that replaceNode removes the node that invokes the method from the document hierarchy, and swapNode moves the node that invokes the method to the position of the incoming node. The following sample code highlights the use of both methods.
<SCRIPT>
window.onload=fnInit;
function fnInit(){
   var oNewPara=document.createElement("P");
   var oText=document.createTextNode("This is the new paragraph");
   oNewPara.appendChild(oText);
   document.body.appendChild(oNewPara);
   // Paragraph 2 is replaced with the new paragraph
   oP2.replaceNode(oNewPara);
   // The position of paragraph 1 is exchanged with the new paragraph
   oNewPara.swapNode(oP1);
}
</SCRIPT>

<P ID=oP1>This is the first paragraph</P>
<P ID=oP2>This is the second paragraph</P>
The ability to manipulate nodes allows authors to perform complex operations on the document without rewriting the content. Speed and efficiency are gained by working directly with the document tree. Being able to navigate and identify nodes, create new nodes, and manipulate existing nodes prepares authors to make the most of their creativity and ingenuity when developing dynamic documents.

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

Open Hardware Monitor A Handy Tool for System Monitoring

#Open #Hardware #Monitor: A Handy Tool for #System #Monitoring #OpenHardwareMonitor is a free, #opensource #software designed to monitor t...