What is Mojo::DOM text?

Overview

The text method extracts the text content from the given element. This won’t include the child elements. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

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

Return value

This method will return the extracted text from the given element.

Let’s look at an example of this:

Code

The given HTML is as follows:

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

If we extract the text content from the given element div, we will get the following output for the given HTML:

Inside div 
use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside first paragraph </p><p id="b">Inside second paragraph</p></div>');
# Extract the text content for the given element
say $dom->at('div')->text;

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 extract the text content from the given element div and print it to the console.

Free Resources