Get the source code of an element

Viewed 3710

Is there a similar way in Laravel Dusk as we have in Selenium, to get the source code of an element by 'innerHTML attribute'?

Ex: innerHTML for <div>Hello <p>World!</p></div> would be: Hello <p>World!</p>.

2 Answers

To get source code of element you should use element() method together with getAttribute like this:

$this->browse(function(Browser $browser) {

    $html = $browser->visit('/')
                    ->element('div.content')
                    ->getAttribute('innerHTML');

   // now in $html you have HTML inside div.content element
});

Be aware in case you have multiple elements with given selector you should use elements() method and iterate over found elements to get their content like this:

$this->browse(function(Browser $browser) {
    $elements = $browser->visit('/')
                        ->elements('div.content');

    $html = [];
    foreach ($elements as $element) {
        $html[] = $element->getAttribute('innerHTML');
    }

    // now in $html you have array of HTML inside div.content elements
});

I'm not familiar with Selenium innerHTML but with Dusk you can assert directly against the source code via $browser->assertSourceHas($code).

You'll get to see the full source code of your site if the assertion fails.

public function testSourceCode()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSourceHas('Hello <p>World!</p>');
        });
    }
Related