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 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 preceding siblingssay $dom->at('h2')->preceding->join("\n");
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
precedingmethod to get the preceding sibling elements for the given elementp. Next, we print the returnedMojo::DOMcollection.