What is the replace method in Mojo::DOM?

Overview

The replace method replaces the specified HTML/XML element with the given HTML/XML element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

$dom->at('old html element')->replace('new html element')

Return value

This method will replace the given node and return a parent or root element.

Let’s look at an example of this.

Code

use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside paragraph </p></div>');
# replace node p
say $dom->at('p')->replace('<h1>This is a new element</h1>');

Explanation

In the code snippet above:

  • In line 2, we import the Mojo::DOM module.
  • In line 5, we parse the HTML and store it in the $dom scalar.
  • In line 8, we replace the node p with the h1 element using the replace method and print the returned parent or root element.

Free Resources