What is the preceding_nodes method in Mojo::DOM?

Overview

The preceding_nodes method finds the preceding sibling nodes for the given element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOMData Object Model parser with CSS selectors.

Note: The preceding method returns preceding sibling elements, while preceding_nodes returns preceding sibling nodes.

Syntax

$dom->preceding_nodes

Returns

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

Note: A Collection is a group of objects or elements.

Let’s take a look at an example.

Example

A sample HTML code is given below:

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

If we find the preceding sibling nodes for the given h2 element using the preceding_nodesmethod, we get the following output:

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

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 preceding sibling nodes
say $dom->at('h2')->preceding_nodes->join("\n");

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 8: We get the first descending element, h2, using the at() method. We find the preceding sibling nodes for the given h2 element using the method preceding_nodes. Then, we print each Mojo::DOM object in a new line by joining the new line, \n , using the join() method.

Free Resources