Client-side
DOM (& JavaScript)

Parke Godfrey
6 November 2012
CSE-2041

Credits

These slides are based in part on ones from the following sources.

DOM: Document Object Model

HTML DOM tree

HTML DOM Tree (from W3Schools.com).

  • DOM is an object model for XML.

  • HTML DOM is an object model for HTML.

  • DOM represents an XML / HTML document as nested objects.

  • The Web browser creates a DOM object to represent a page it is presenting.

  • User actions — and JavaScript-triggered actions — interact with that DOM object.

The DOM Tree

<html>
  <head>
    <title>DOM Tutorial</title>
  </head>
  <body>
    <h1>DOM Lesson one</h1>
    <p>Hello world!</p>
  </body>
</html> 
		
DOM navigation

DOM relations (from W3Schools.com).

  • Each object is called a node.

    DOM node = HTML element

  • Each node has a parent, and can have children and siblings.

DOM
node properties

Some (HTML) DOM node properties:


  • x.innerHTML: the text value of x. (Not in the standards!)
  • x.nodeName: the tag name of x.
  • x.nodeValue: the value of x.
  • x.parentNode: the parent node of x.
  • x.childNodes: the child nodes of x.
  • x.attributes: the attribute nodes of x.

Note that x is an object representing that DOM node.

How do we get the object?

DOM
node methods

Some (HTML) DOM node methods:


  • x.getElementById(id): get the element by a specified id.
  • x.getElementsByTagName(name): get all elements with a specified tag name.
  • x.appendChild(node): insert a child node to x.
  • x.removeChild(node): remove a child node from x.

The root of an HTML DOM tree is the node document.

DOM
a note about text

Text content within an element is implicitly placed within a #text child node.

This can really trip you up, unless you know about it!

Why is this done?

DOM
events

Events are actions that can trigger JavaScript functions.


Some DOM events are:

  • onload: triggered when the element is finished loading.
    (Can be attached to <body> and <img>.)
  • onunload: triggered as the page is being exited.
  • onclick: triggered when the element is clicked.
  • onfocus: triggered when the element gains focus.
  • onblur: triggered when the element loses focus.

See W3School's HTML DOM Event Object for more.

JavaScript with DOM
examples