Skip to content

What is DOM?

Greg Bowler edited this page Jun 20, 2017 · 6 revisions

DOM (Document Object Model) is a W3C standard defining an object oriented representation of the HTML within a webpage. It allows you to manipulate and traverse the page in your code through a hierarchical tree of elements. Elements of the document all have standardised methods and properties allowing you to find and interact with their parents, children and siblings.

There are multiple uses of DOM in web programming: Quickly turn a static HTML document dynamic by using PHP to update the content of elements, reuse parts of pages to enhance or replace template engines, and use the existing capabilities of HTTP to create dead simple database-driven forms.

Really simple example

Consider an HTML page showing a "quote of the day". In HTML we can create a heading element followed by an empty paragraph element:

<h1>Quote of the day</h1>
<p id="output"></p>

Then in PHP, we can use DOM to access the paragraph by it's ID, and set its textContent to a random quote from the database:

$quote = $database->getRandomQuote();
$paragraphElement = $document->getElementById("output");
$paragraphElement->textContent = $quote;

Accessing elements by their ID is the simplest way to reference specific elements, but there are many different methods of traversing the tree in DOM.

Take a look at some other simple example applications to get more familiar with DOM.


Up next: Using DOM in PHP.