My Adsense

Saturday, July 9, 2011

HTML Document Object Model

What is it?
The HTML DOM defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a tree-structure.
In the DOM, everything in an HTML document is a node.
The DOM says:
  • The entire document is a document node
  • Every HTML element is an element node
  • The text in the HTML elements are text nodes
  • Every HTML attribute is an attribute node
  • Comments are comment nodes
Example Node tree:
From the HTML above:
  • The < html > node has no parent node; it is the root node
  • The parent node of the < head > and < body > nodes is the < html > node
  • The parent node of the "Hello world!" text node is the < p > node
  • The < html > node has two child nodes; < head > and < body >
  • The < head > node has one child node; the < title > node
  • The < title > node also has one child node; the text node "DOM Tutorial"
  • The < h1 > and < p > nodes are siblings, and both child nodes of  < body >
It has some properties and methods as well.
Some DOM properties:
  • x.innerHTML - the text value of x
  • x.nodeName - the name of x
  • x.nodeValue - the value of x
  • x.parentNode - the parent node of x
  • x.childNodes - the child nodes of x
  • x.attributes - the attributes nodes of x
Note: In the list above, x is a node object (HTML element).
Some DOM methods:
  • x.getElementById(id) - get the element with a specified id
  • x.getElementsByTagName(name) - get all elements with a specified tag name
  • x.appendChild(node) - insert a child node to x
  • x.removeChild(node) - remove a child node from x
Note: In the list above, x is a node object (HTML element).
DOM Methods details:
getElementById(parameter): gets the element which has the id equals to the parameter
getElementsByTagName(parameter): gets the element which is the html tag equals to the parameter
Working with DOM code snippets:
document.body.bgColor="lavender"; //changes the document's background color
document.getElementById("p1").innerHTML="New text!"; // replaces the text of all p1 id element with "New text"
< input type="button" onmouseover="document.body.bgColor='green'" onclick="document.body.bgColor='lavender';" value="Change background color" / >
.style : this property indicates you can also work with the element's style values
Examples of events:
  • A mouse click
  • A web page or an image loading
  • Mousing over a hot spot on the web page
  • Selecting an input box in an HTML form
  • Submitting an HTML form
  • A keystroke
Example: < input type="text" id="email" onchange="checkEmail()" / >
For more: visit W3Schools

No comments: