Jegsworks: Free Online Computer Lessons Logo:Jegsworks Jan's Illustrated Computer Literacy 101


Home > Resources & Examples > Jan's Web Scripting Demo > DOM

Icon: Arrow - Previous pagePrevious    NextIcon: Arrow - Next page


Jan's Web Scripting Demo: DOM

The Document Object Model (DOM) for HTML documents defines the relationships among the parts of an HTML document and some methods for accessing the part you want to change. It's somewhat like needing to know the full name of a person in order to find out their phone number or other contact information. If you don't know the person's name and how it is constructed (is the family name first or last?), it's really hard to communicate!

When your browser loads an HTML page, it automatically creates a Document Object Model for the page. The DOM can be represented as a tree of related objects.

The DOM defines the HTML elements as objects, properties for each element, methods to access these elements and their properties, and events for all HTML elements. So with JavaScript you can add, delete, or modify every element and every property of an element on your HTML page. Cool.

Example: DOM hierarchy and the HTML code for it

Click on the parent HTML element below and then on each child element in the diagram. Tags for that part will show below. Tags for a child element will not show unless the parent elements already show. Click a box again to hide that part.

Example: Document Object Model tree for example page

Show all tags

   

The tags above are the skeleton of the page DOM in Action Icon: On Site

Open the exampleIcon: On Site in a new tab or window and view the page source. It's a lot more complex than you might expect from the tags above!


Attributes

Each element in the object tree has its own attributes. The most useful global attributes include id, class, title, and style. Useful HTML event attributes include onLoad, onClick, onMouseOver, and onMouseOut. Some elements have their own special attributes, like SOURCE and ALT for an IMG tag.


Access an Element

The most common way to access an HTML element from JavaScript is to assign it an ID in its tag and use the method getElementById() in your script.

[Note that correct capitalization is critical in Javascript!]


What to do with Javascript

Change content: You can change the HTML content of an element by changing the property innerHTML for the element.

Show/hide content with onClick: The display property was changed from 'none' to 'block' on this page when you clicked on one of the DOM hierarchy boxes.

Change formatting with event: In the example page, scripts in the HEAD and inline scripts were used with the onMouseOver and onMouseOut events to change formatting back and forth.

Next, we will see exactly how to create some of the effects illustrated on the introduction page.


 

HTML head body meta title style script h1 h2 div p p inside a div img inside a div