Contents |
The document object model, or DOM, is the platform/language independent model for representing an HTML document. The DOM has been standardized by the W3C. You can find all of the information you ever wanted to know about the DOM and more at their site. The presence of a DOM allows languages such as JavaScript the ability to easily manipulate the final presentation of a web page.
Manipulation of the HTML DOM will cause immeadiate changes to occur from a users point of view as they look at a web page. If you add an element to the DOM, the user will see it on the page right then. This makes for a very nice user experience if done correctly. If done poorly, it can be much worse then SPAM or pop-up adds! No one likes a page that changes sporatically and in an incomprehensible way. If things change on a web page the user should expect it to happen.
A node object has a nice set of properies to find all of its relatives. You can find the children of an object by interating through the list available in the childNodes array, or you can directly get the firstChild or the lastChild. You can find the containing node by using the property parentNode. You can also find the previousSibling or the nextSibling. If you want access to all sibling nodes, you can access the parentNodes's childNodes array. The following examples will use some of these properties.
The following example shows how to change a bit of text by clicking on a button.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules!</title>
<script type="text/javascript">
function changeit(){
var _mydiv = document.getElementById('mydiv');
_mytext = _mydiv.firstChild;
_mytext.data = "You clicked my button!";
}
</script>
</head>
</body>
<input type="button" id="mybutton" name="mybutton" value="Click Me" onclick="changeit()" />
<div id="mydiv">This is my text</div>
</body>
</html>
When the button is clicked, the changeit function is called. The changeit function uses the getElementById function to find the HTML element with the id of mydiv. If you look at the HTML, you will see that this element is a DIV tag with some text in it. A JavaScript variable is populated with an Element object that represents this DIV tag. The Element object is a subclass of Node. The next line of code accesses the inherited firstChild property of the Element object. In this example the only child of the Element is the text in the DIV tag. If your code was not sure what was inside the Element there is a series of methods and properties available to search through the children of the Node. Next, the data property of the child is set to a new value. Again, there is a nice set of methods to use for manipulating the data if you need them. This is immediately reflected in the HTML page viewable to the user.
The code below will create a new <h;h1> tag and put some text in it. The tag will then be added to the page for presentation.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules!</title>
<script type="text/javascript">
function addit(){
var _mydiv = document.getElementById('mydiv');
_myh1 = document.createElement('h1');
_mytext = document.createTextNode('You pushed my button!');
_myh1.appendChild(_mytext);
_mydiv.appendChild(_myh1);
}
</script>
</head>
</body>
<div id="mydiv" style="border: 2px solid blue;">This is my text</div>
<input type="button" id="mybutton" name="mybutton" value="Click Me" onclick="addit()" />
</body>
</html>
A couple of new things are introduced in this new bit of code. The first the the createElement function. This method is available through the document object. It will create any valid HTML element object based on the tag name. The next new method is the createTextNode method. This method is also available as part of the document object. This method will, as the name clearly represents, create a text node that can be added to any HTML element that will accept text between its opening and closing tags. The third new method shown in this example is the appendChild method. This method will take any valid Node object and add it as the last child of another object. If you want the new child added somewhere other than as the last child, you can use the methods insertBefore method. This method takes one more parameter, the child node that the new node should be inserted before.
The following example shows how to remove document elements.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules!</title>
<script type="text/javascript">
function removeit(){
var _mydiv = document.getElementById('mydiv');
_mydiv.removeChild(_mydiv.firstChild);
}
</script>
</head>
</body>
<div id="mydiv" style="border: 1px solid black;">
<div style="border: 2px solid blue;">First Child</div>
<div style="border: 2px solid green;">Second Child</div>
</div>
<input type="button" id="mybutton" name="mybutton" value="Click Me" onclick="removeit()" />
</body>
</html>
The JavaScript to remove the element is clear enough, you just pass the Node object that you want removed to the removeChild method. It is immeadiately removed from the HTML page. The method returns the object that is removed so that you can use it else where in the document if you want.
This example does show an interesting aspect of DOM processing. If you run the above code in Firefox, the first time you click the button, you will not see any change to the document. The second click of the button will remove the first child DIV element. What that first click removes is the whitespace between the mydiv opening DIV tag and its first child div tag. In the DOM, every character counts. Internet Explorer on the other hand will often ignore the nodes with only whitespace in them. This incompatibility may cause you problems. L. David Baron wrote a great article and supplied some code for dealing with this problem.
One of the properties of the Element object is the style property. The style property is an object itself that represents all of the CSS2 attributes that the element has. The example below changes a few style properties.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX Rules!</title>
<script type="text/javascript">
function styleit(){
var _mydiv = document.getElementById('mydiv');
_mydiv.style.fontSize = "30px";
_mydiv.style.color = "red";
}
</script>
</head>
</body>
<div id="mydiv" style="border: 1px solid black;">This is my text</div>
<input type="button" id="mybutton" name="mybutton" value="Click Me" onclick="styleit()" />
</body>
</html>
The example above changes the font size and color of the DIV element. There are a few things to take note of when working with the style object. All of the CSS2 attributes are available, but the names may have been changed. Any CSS attribute that with dash(-) was changed by removing the dash and making the property name [[wikipedia:camelCase|]. For example, the CSS attribute font-size is available as the fontSize property of the style object. The float attribute was changed to cssFloat because float is a reserved word in JavaScript.
All property values are stored as strings. This is important to note if you are working with a value that represents a number. For example, say you want to increase a font size by 5px. You will need to retrieve the value from the fontSize property and then pass that value to the parseFloat function. The parseFloat function will return a valid number to which you can add 5. After changing the value you must store it back in the propery as a string. You can easily do this by concatinating the value the the proper unit, such as px. You could alter the above example like this:
function styleit(){
var _mydiv = document.getElementById('mydiv');
var myFontSize = _mydiv.style.fontSize;
myFontSize = parseFloat(myFontSize) + 5;
_mydiv.style.fontSize = myFontSize + 'px';
_mydiv.style.color = "red";
}
You will want to use parseFloat instead of parseInt because CSS allows float values for all of its numeric attributes.
There is a lot of power available to change the presentation of a page any way you want. But, never forget that "with great power comes great responsibility." JavaScript should be used to make the user experience better not confusing.
There is a lot of information that was not covered in this short article. There are far to many objects, methods and properties to cover them all in depth here. Purchasing a good book on the subject might be in order. I personally use the O'REILLY JavaScript Pocket Reference. This is a great book that give a susinct description of every object and their methods and properties. It also give some hints as to browser compatibility. There are probably a lot of good books out there, but this is the one I happen to own. Probably because it only cost about $10.
http://www.w3schools.com/htmldom/dom_intro.asp
http://www.w3schools.com/htmldom/dom_examples.asp
http://www.w3.org/DOM/
http://www.w3schools.com/htmldom/dom_reference.asp
© 2009 Novell, Inc. All Rights Reserved.