What is the content method in Mojo::DOM?

Share

Overview

The content method gets the content for a given element or replaces the content present in the same element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

We use the following syntax to get the content:

$dom->at('html element')->content

We use the following syntax to replace the content:

$dom->at('html element')->content('new content')

Return values

  • content: This method returns the given node's content.
  • content('new content'): This method returns the Mojo::DOM object after replacing the content with new content.

Let’s take a look at an example.

Example

A sample HTML code is given below.

<div>
Inside div
<p id="a"><span>Inside first paragraph</span> </p>
<p id="b">Inside second paragraph</p>
</div>

If we try to get the content for the span element using the content method, we get the following output:

Inside first paragraph

Code

use 5.010;
use Mojo::DOM;
# Parse the HTML
my $dom = Mojo::DOM->new('<div>Inside div <p id="a"><span>Inside first paragraph</span></p><p id="b">Inside second paragraph</p></div>');
# Get the content
say $dom->at('span')->content

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the scalar $dom.
  • Line 8: We print the content for the given element span using the content method.

Let's now take a look at how to replace the content for the given element.

Code

use 5.010;
use Mojo::DOM;
# Parse the HTML
my $dom = Mojo::DOM->new('<div>Inside div <p id="a"><span>Inside first paragraph</span></p><p id="b">Inside second paragraph</p></div>');
# Replace the content
say $dom->at('div')->content("Replaced content in div")

Explanation

  • Line 8: We replace the content for the div element, and print the Mojo::DOM object with the new content.