Document traversal
CSS selectors in PHP
The library supports selector-based traversal through:
$card = $document->querySelector(".product-card");
$buttons = $document->querySelectorAll("form[action] button");
$section = $card?->closest("section");
Internally, selectors are translated to XPath. In normal use that is an implementation detail, but it matters in one practical way: invalid selectors raise XPathQueryException.
Live versus static collections
This library follows the DOM’s distinction between live and static collections.
HTMLCollection is live
Methods and properties such as these return a live HTMLCollection:
childrengetElementsByTagName()getElementsByClassName()- document-wide properties such as
forms,images,links, andscripts
$forms = $document->forms;
$document->body->appendChild($document->createElement("form"));
echo $forms->length; // now includes the new form
querySelectorAll() returns a static NodeList
This matches browser behaviour:
$items = $document->querySelectorAll("li");
If the document changes afterwards, that particular result set does not update.
getElementsByName() returns a live NodeList
This is one of the places where the return type is NodeList, but the behaviour is live.
Collection helpers
The collection objects are intentionally array-like and iterable in PHP:
foreach($document->images as $image) {
$image->loading = "lazy";
}
$first = $document->links[0] ?? null;
Useful MDN references:
Child and parent helpers
The server-side API includes the browser-style convenience methods:
$notice = $document->querySelector(".notice");
$notice?->before($document->createElement("hr"));
$notice?->after("Updated just now");
These are often more pleasant than the older insertBefore()-style calls when we are doing small structural edits.
[!TIP] In WebEngine applications, it is worth checking whether DomTemplate can express the page update before writing repeated manual selectors.
With traversal covered, the next page looks at the HTML-specific conveniences and the places where server-side DOM naturally differs from browser DOM: Working with HTML-specific helpers.