What is the previous_node method in Mojo::DOM?

Overview

The previous_node method is used to find the previous sibling node for the given element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Note: The previous method returns the previous sibling element, while the previous_node returns the previous sibling node.

Syntax

$dom->previous_node
Syntax of the previous_node method

Return value

This method returns the previous node for the given 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>
Sample HTML code

If we find the previous sibling node for the h1 element using the previous_node method, we get the following output:

After paragraph
Note: Using previous here would have returned <p id="a">Inside paragraph </p>.

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 previous sibling node
say $dom->at('h1')->previous_node

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 previous_node method to get the previous sibling node for the h1 element, and print the returned Mojo::DOM object.

Free Resources