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
Note: Thepreceding
method returns preceding sibling elements, whilepreceding_nodes
returns preceding sibling nodes.
$dom->preceding_nodes
This method returns the Mojo::Collection
which contains each node as a Mojo::DOM
object.
Note: ACollection
is a group of objects or elements.
Let’s take a look at an 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_nodes
method, we get the following output:
Inside div<p id="a">Inside paragraph </p>After paragraph<h1>Inside h1</h1>After h1
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>After h1<h2>Inside h2</h2></div>');# Get preceding sibling nodessay $dom->at('h2')->preceding_nodes->join("\n");
Mojo::DOM
module.Mojo::DOM
object with the new
keyword and parse the HTML. We then store it in the $dom
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.