Sunday, November 19, 2006

DOM - Part Two - How to get a node easily?

Walk through in a more elegant way:

As we can see that walking through the DOM tree is actually very troublesome. If there are thousands of tags in your document, and what you need is just a particular one deep inside several nesting, I guess you'll simply give up if only method mentioned in first part in available. However, for programmers' convenience, DOM does have some support for fast access to particular nodes.

The first way is to get the element by its tag.So let's continue with our example. You want to access the element node B. The very simplest way is to directly jump to it. By the method document.getElementsByTagName you can construct an array of all tags B in the document and then go to one of them. Let's assume that this B is the first one in the document, then you can simply do

var x = document.getElementsByTagName('B')[0]
Or we can do it more directly, get an element by its name. The usage is even more straight forward:

var x = document.getElementById('hereweare');

Here if we've assign an element's id with "hereweare", the function will return the index to the element. Then we can manipulate the element in whatever way we want.

Example: Why we need DOM?

Actually, before DOM we can already access element quite easily in Javascript. Like in IE, we may just write:

void function hide(x)
{
x.style.visibility="hidden";
......
......
}


then call the function with element's id, like

hide("hello");
Then the element with Id "hello" will be manipulated with the statements in funciton hide().

However, it will easily generate problems. The value passed to the function is actually a string, not an index to element. It confuses programmer sometimes. In order to make the code more readable and standardized, we should adopt DOM instead of the method mentioned above. Actually, in Firefox we can only use DOM to access elements.

To make the function standardized, we need to modify it a little bit:

void function hide(name)
{
var x=getElementById(name);
x.style.visibility="hidden";
......
......
}




referrence: http://www.quirksmode.org/dom/intro.html

0 Comments:

Post a Comment

<< Home