Monday, November 8, 2010

Document Object Model (DOM)

What is Document Object Model (DOM)?
  • is an API for valid HTML and well formed XML documents
  • defines the logical structure of documents and the way a document is accessed and manipulated
  • With DOM programmers can build documents, navigate thier structure, and add, modify or delete styles, attributes, elements and contents
  • Infact anything found in an HTML or XML document can be accessed, changed, deleted or added using DOM, with a few exceptions
  • Can be accessed via any language in the browser including Java, JavaScript/ECMAScript/JScript and VBScript (IE only)


Few Terms
  • Node: A reference to
    • an element (tag) and its attributes
    • or a piece of text
  • Element: A representation of a
  • Attribute: A property of an element. HREF is an attribute of element for example


Detecting Browser Compatibility
  • To detect browser support for a particular DOM property or method we want to use we have to use “object detection”
    • Example: In the DOM most commonly used method is document.getElementById. To detect browser support for this method before proceeding with our DOM related code, we have to check the suport like this:
      • If (document.getElementById)
      • document.getElementById(“div”).getAttribute(“align”)
      • Add Elements to the DOM
  • Steps
    • create the node (text node or element) you wish to append
      • To create a new text node use a createTextNode() method of document object that will return a node with given text in it
      • var txtNode = document.createTextNode("Hello. This is a new node.");
      • To create a new element and set attributes on it
      • var link = document.createElement('a');
      • link.setAttribute('href', 'mypage.htm');
    • find where you wish to append it within the document tree using getElementById method of document object that will return an object
      • var myDiv = document.getElementById("myDiv")
    • actually do the appending
      • To append at the end of the div
      • myDiv.appendChild(txtNode); or
      • document.getElementById('myDiv').appendChild(link);
      • To append at the beginning of the div
      • myDiv.insertBefore(link, document.getElementById('myDiv').firstChild);

  • Copy this working example to new html file and try it.


Click here to generate yahoo website link


This text is the first child of mylinkdiv


To Hide/Show any element
  • To dynamically hide/reveal any element on the page using DOM try this example


Click here to hide/show below element




You can see it now


To add textbox and define onchange event on it
  • To dynamically add textbox and define onchange event on it, try following:


http://www.w3.org/TR/DOM-Level-2-Core/introduction.html
http://www.javascriptkit.com/javatutors/dom.shtml

No comments:

Post a Comment