What is the to_string method in Mojo::DOM?

Overview

The to_string method renders the given node and its contents to an HTML/XML string. This method is provided by the Mojo::DOM module, which is an HTML/XML DOMData Object Model parser with CSS selectors.

Syntax

my $str = $dom->to_string;

Return value

This method returns a string of HTML/XML for the given node and its contents.

Let’s take a look at an example.

Example

In the following example, we will try to render the given node and its contents to an HTML/XML string.

Code

use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside paragraph </p>After paragraph<h1>Inside h1</h1>After h1<h2>Inside h2</h2></div>');
# get rendered string
my $str = $dom->at('p')->to_string;
say $str

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We construct a Mojo::DOM object with the new keyword and parse the HTML. We then store it in the $dom scalarA scalar is a variable that stores a single unit of data..
  • Line 10: We get the first descending element, p, using the at() method. We render the p node and its contents to the HTML/XML string using the to_string method.
  • Line 12: We print the str string returned in line 10.