What do people mean by "DOM Manipulation" and how would I do that?

I always hear people talk about DOM this, manipulate the DOM, change the DOM, traverse the DOM; but what exactly does this mean?

What is the DOM and why would I want to do something with it?


The DOM is basically an API you use to interface the document with, and is available in many languages as a library ( JS is one of those languages ). The browser converts all the HTML in your web page to a tree based on the nesting. Pop open Firebug and look at the HTML structure. That is the tree I'm talking about.

If you want to change any HTML you can interact with the DOM API in order to do so.

<html>
 <head><script src="file.js"></script></head>
 <body>blah</body>
</html>

In file.js I can reference the body using:

onload = function() {
    document.getElementsByTagName('body')[0].style.display='none';
}

The getElementsByTagName is a method of the document object. I am manipulating the body element, which is a DOM element. If I wanted to traverse and find say, a span I can do this:

onload = function() {
 var els = document.getElementsByTagName('*');
 for ( var i = els.length; i--; ) {
    if ( els[i].nodeType == 1 && els[i].nodeName.toLowerCase() == 'span' ) {
       alert( els[i] )
    }
 }
}

I am traversing the nodeList given back by getElementsByTagName in the snippet above, and looking for a span based on the nodeName property.


It means working with the Document Object Model, which is an API to work with XML like documents.

From w3 on the DOM:

The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page. This is an overview of DOM-related materials here at W3C and around the web.

One of the functions mostly used in DOM work is:

getElementById

Manipulating/Changing the DOM means using this API to change the document (add elements, remove elements, move elements around etc...).

Traversing the DOM means navigating it - selecting specific elements, iterating over groups of elements etc...


In short:

When a web page is loaded, the browser creates a Document Object Model of the page, which is an object oriented representation of an HTML document, that acts as an interface between JavaScript and the document itself and allows the creation of dynamic web pages.

Source: w3schools - HTML DOM