Skip to content

An introduction to the Document Object Model

Greg Bowler edited this page May 16, 2016 · 6 revisions

The Document Object Model (DOM) is a hierarchical data structure for representing and interacting with elements of HTML and XML documents. A good overview of the DOM can be found in the Mozilla Web APIs documentation.

PHP natively bundles libxml, a very portable XML parser, upon which this project is built. As standard, libxml fully implements DOM Level 2 Core which includes base concepts such as Nodes, Elements, Documents and NodeLists, and this project aims to bring DOM Level 4 and beyond to PHP.

## Quick-hit feature list.

Using title, querySelector and textContent, change the page title to the contents of the first H1 on the page.

$document->title = $document->querySelector("h1")->textContent;

Using querySelectorAll and classList, add the 'selected' class to the navigation link that matches the current request URI.

$document->querySelectorAll(
    "body>nav li>a[href='$_SERVER[REQUEST_URI]']"
)->classList->add("selected");

Why perform DOM manipulation on the server?

When working on non-trivial web projects, being able to manipulate the page as a tree of elements can speed up the render time and also greatly enhances development efficiency and maintainability of projects. Being able to traverse the page via its element hierarchy means areas of code can manipulate the page in isolation from each other, without having to re-parse and re-render the page for each edit (like many mainstream frameworks do).