2. JavaScript and the DOM

Last modified: January 9, 2009 - 10:06

The Document Object Model (DOM) is an API for HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation. Essentially, it connects web pages to scripts or programming languages.
- the DOM section at mozilla.org

The DOM is what connects your js code to your HTML page.
It has a tree structure that JavaScript can navigate very easily, as follows:
document.documentElement.firstChild
document.documentElement gets you the root element, which in the case of an html document is always the <html> element. From there you are getting the first child node of that element, i.e. the <head> element. As you can imagine, this kind of node by node navigation of the DOM can only get you so far and luckily there are two standard DOM methods implemented by JavaScript for quickly accessing elements in your page: getElementById() and getElementsByTagName().
Here's an example of how you can use them:

var myId = document.getElementById("myId");
myId.style.border = "1px solid #999";
var li = document.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
  li[i].style.border = "1px solid #999";
}

This code will add a grey border both to the element with the id of "myId" and to all li elements on the page. Note how the for loop is done exactly the same as in php. This example doesn't quite demonstrate JavaScript's real power because there's one vital thing missing: user interaction. Events - such as mouse-clicks, keypresses, page loads, mouse movement - are the ingredients that give JavaScipt its purpose on the web. Once these are added, it doesn't take much imagination to realise the endless possibilities there are for manipulating our pages using JavaScript in combination with the DOM. The example below creates and displays an entirely new element with the content "hello" when a user clicks on any link:
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
  links[i].onclick = function(e) {
    var div = document.createElement("div");
    div.className = "myDiv";
    div.innerHTML = "hello";
    var parent = this.parentNode;
    parent.appendChild(div);
    return false;
  }
}

And remember, this is still just regular old JavaScript code, not jQuery. It is valid to use regular JavaScript code in your Drupal pages and completely disregard jQuery, but when you see the power of the latter it's unlikely you will want to. In particular, when you realise that the above will only work in non-IE browsers but jQuery will enable you to write a cross-browser version of it in all of three lines...

Before exploring jQuery, you might want to do some further reading on the DOM:

 
 

Drupal is a registered trademark of Dries Buytaert.