What is the find() method in Mojo::DOM?

Overview

The find() method will find all the descendant elements for the given element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

$dom->find('html element')

Return value

This method will return all the descendant elements as Mojo::Collection where each element is a Mojo::DOM object.

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><h1>Inside heading 1</h1></div>');
# find descendants for div
say $dom->find('p')->map('tag')->join("\n");

Explanation

In the code snippet above:

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in scalar $dom.
  • Line 8: We get all descendants of the element p for the given HTML using the find method and print all tag names present in the returned Mojo::Collection.

Free Resources