Introduction to W3C DOM

In this tutorial we will learn how to use the DOM tree to add a new element to a page and to fill that element with text. We will create an HTML page that will include a form to input the text and select the CSS class for the new element, a CSS stylesheet and a javascript page. In particular we will be dealing with the following methods:

getElementById() - reference an html element by its id
createElement() - create a new html element
appendChild() - Add a node to specified element
createTextNode() - As it sounds
x.lastChild - references the last child node of x

First we create a stylesheet and define 3 distinct classes

Next we create an HTML document and attach the stylesheet

It is worth noting here that the form and div are both 'child' elements of the body tag and the input tags are 'child' elements of the form tag. Or to reverse the statement the form tag is the parent of the input tags and the body tag is parent to the form and div tags.

It is also worth noting that different browsers interpret white space between elements differently, some will add it to the node heirarchy and some will ignore it

The next step is to create the javascript function that will add the new element to the page. Create a new .js file and add the following code

if you havn't already attach the javscript file to your HTML document

And finally we add the call to the javascript function in the select tag on the HTML page. Modify the select tag as follows:

Thats it! Now go to Introduction to W3C DOM | part 2

Links:

Introduction to W3C DOM | part 2

quirksmode.org is an invaluable resource for anyone using DOM. It is important that you familiarise yourself with the compatability charts you will find there.

tags

Comments:

Featured Script

Javascript image replacement of text links
This script allows you to replace the text links in your page with images. Full working example and ... (read more)