What is the preceding method in Mojo::DOM?

Overview

The preceding method is used to find the preceding sibling 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->preceding
Syntax of the preceding method

Return value

This method returns the Mojo::Collection, which contains each element as a Mojo::DOM object.

Example

A sample HTML code is given below:

<div>
Inside div
<p id="a">Inside paragraph </p>
After paragraph
<h1>Inside h1</h1>
<h2>Inside h2</h2>
</div>

If we find the preceding siblings for the given element, h2, using the preceding method, we get the following output:

<p id="a">Inside paragraph </p>
<h1>Inside h1</h1>

Code example

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><h2>Inside h2</h2></div>');
# Get preceding siblings
say $dom->at('h2')->preceding->join("\n");

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 use the preceding method to get the preceding sibling elements for the given element p. Next, we print the returned Mojo::DOM collection.

Free Resources