PHPerKaigi 2025

Dom\ParentNode::querySelector

(PHP 8 >= 8.4.0)

Dom\ParentNode::querySelectorReturns the first element that matches the CSS selectors

Description

public Dom\ParentNode::querySelector(string $selectors): ?Dom\Element

Returns the first element that matches the CSS selectors specified in selectors.

Parameters

selectors
A string containing one or more CSS selectors.

Return Values

Returns the first Dom\Element that matches selectors. Returns null if no element matches.

Errors/Exceptions

Throws a DOMException with code Dom\SYNTAX_ERR when selectors is not a valid CSS selector string.

See Also

add a note

User Contributed Notes 1 note

up
0
kawewong at gmail dot com
6 hours ago
Even the document said "This is the modern, spec-compliant equivalent of DOMParentNode" but in DOMParentNode page there is no new methods like `querySelector()`.

To use this method you have to use new class.
Example:

<?php
$html
= <<<EOT
<div class="row">
<div class="col"><h1 id="heading" class="col1-heading">Hello</h1></div>
<div class="col"><p class="paragraph">Hello world.</p>
</div>
EOT;
$doc = \DOM\HTMLDocument::createFromString($html, LIBXML_HTML_NOIMPLIED);
$elem = $doc->querySelector('#heading');
echo
$elem->getAttribute('class');// result is col1-heading
?>
To Top