Symfony DomCrawler how to insert html after some element?

2.4k Views Asked by At

The HTML content

<div class="card mb-3 template">
    <div class="card-body">
        <div class="row mt-3">
            <div class="col-sm-4">
                <h4>This is title</h4>
            </div>
            <div class="col-sm-8 text-right">
                <button>Close</button>
            </div>
        </div>
    </div>
</div>

I want to insert a div element after <h4>, e.g.

<div class="col-sm-4">
    <h4>This is title</h4>
    <div class="status"></div>
</div>

In jQuery is pretty easy

$('<div class="status"></div>').insertAfter($('.template').find('h4'));

But, how can I do this in DomCrawler ?

$crawler = new \Symfony\Component\DomCrawler\Crawler($html);
$nodes = $crawler->filter('.template');
foreach ($nodes as $node) { // there are multiple template
    // so how to insert the div element after h4
}
1

There are 1 best solutions below

0
On

Symfony DomCrawler is just a fancy wrapper for PHP's built in DOMDocument class. Using getNode will get the DOMNode object of the element you will need to perform the "insertAfter" method.

$crawler = new \Symfony\Component\DomCrawler\Crawler($html);
$domDocument = $this->crawler->getNode(0)->parentNode; //this is how you get domDocument

//creating div
$div = $domDocument->createElement('div');
$div->setAttribute('class', 'status');

//adding div after h4 tag
$h4 = $crawler->filter('h4')->getNode(0);
$h4->parentNode->insertBefore( $div, $h4->nextSibling);