October 11, 2019 Javier Eguiluz

The DomCrawler component is mostly used in Symfony applications via functional tests, to filter the DOM nodes of HTML/XML documents. The methods provided by DomCrawler were originally inspired by jQuery, such as eq() , first() , children() , nextAll() , etc.

In Symfony 4.4 we've added three new methods frequently requested by the community: matches() , closest() and outerHtml() . Consider the following HTML snippet:

1 2 3 4 5 6 7 8 9 10 11 12 13 < html lang = "en" > < body > < div class = "class-1" > < h1 class = "class-1" > Lorem Ipsum </ h1 > < ul class = "class-2 class-3" id = "id-1" > < li > 1 </ li > < li class = "class-4" > 2 </ li > < li > 3 </ li > </ ul > </ div > </ body > </ html >

The matches(string $selector) method returns true if the node matches the given CSS selector:

1 2 $crawler -> filter ( '#id-1' ) -> matches ( '.class-3' ); // true $crawler -> filter ( '#id-1' ) -> matches ( '.class-4' ); // false

The closest(string $selector) method returns the first ancestor of the node that matches the given CSS selector:

1 2 3 // returns the div.class-1 node and NOT the h1.class-1 node because h1 is // a sibling and not an ancestor of ul#id-1 $crawler -> filter ( '#id-1' ) -> closest ( '.class-1' );

The outerHtml() method returns the whole HTML content of the node, including its own tags:

1 2 3 4 5 // returns '<ul class="class-2 class-3" id="id-1"><li>1</li><li class="class-4">2</li><li>3</li></ul>' $crawler -> filter ( '#id-1' ) -> outerHtml (); // returns '<li>1</li><li class="class-4">2</li><li>3</li>' $crawler -> filter ( '#id-1' ) -> html ();