I have a $foo
which is an instance of Crawler
and $foo->outerHtml()
starts with <div class="brick brick--type--test brick--id--1
. I am writing a test and I'd like to assert brick--id--1
is indeed present as a class. How could I do this? (preg_match()
on $foo->outerHtml()
invokes Cthulhu, I'd rather not)
Asked
Active
Viewed 239 times
0
2 Answers
0
Evaluate an XPATH expression against the nodes to check whether they contain the CSS class.
<?php
require('vendor/autoload.php');
use Symfony\Component\DomCrawler\Crawler;
$html = <<<'HTML'
<!DOCTYPE html>
<html>
<body>
<div class="brick brick--type--test brick--id--1">Hello</div>
</body>
</html>
HTML;
$crawler = new Crawler($html);
$foo = $crawler->filter('body > div');
$class = 'brick--id--1';
$expr = "contains(concat(' ',normalize-space(@class),' '),' $class ')";
$result = $foo->evaluate($expr);
var_dump($result);
// array(1) {
// [0]=>
// bool(true)
// }
var_dump(array_sum($result) !== 0);
// bool(true)

Oluwafemi Sule
- 36,144
- 1
- 56
- 81
-
Thanks. Does the expression need to be this complicated? What does `normalize-space()` buy us? https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/normalize-space says "The normalize-space function strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string." and I do not see that necessary? – chx Nov 23 '22 at 23:13
-
1That's correct what the documentation says. We normalize tabs and newline characters to spaces as well so that we can match them against the '[:space:][classname][:space]' pattern. – Oluwafemi Sule Nov 24 '22 at 13:16
-1
$crawler->matches('.brick--id--1');

Michael Strelan
- 1
- 1
-
Hello, please add any sort of information about your code instead of just submitting a line and leaving it without any context. – Destroy666 May 07 '23 at 19:51
-
The question is "How to check for a class present on an element with Symfony DOMcrawler?" The answer is `$crawler->matches('.brick--id--1');` – Michael Strelan May 08 '23 at 22:06