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: Thepreviousmethod returns the previous sibling element, while theprevious_nodereturns 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: Usingprevioushere would have returned<p id="a">Inside paragraph </p>.
Code example
use 5.010;use Mojo::DOM;# Parse the htmlmy $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 nodesay $dom->at('h1')->previous_node
Explanation
- Line 2: We import the
Mojo::DOMmodule. - Line 5: We parse the HTML and store it in the scalar
$dom. - Line 8: We use the
previous_nodemethod to get the previous sibling node for theh1element, and print the returnedMojo::DOMobject.