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
Note: Theprecedingmethod returns preceding sibling elements, whilepreceding_nodesreturns preceding sibling nodes.
Syntax
$dom->preceding_nodes
Returns
This method returns the Mojo::Collection which contains each node as a Mojo::DOM object.
Note: ACollectionis 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 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");
Explanation
- Line 2: We import the
Mojo::DOMmodule. - Line 5: We construct a
Mojo::DOMobject with thenewkeyword and parse the HTML. We then store it in the$dom .scalar A scalar is a variable that stores a single unit of data
- Line 8: We get the first descending element,
h2, using theat()method. We find the preceding sibling nodes for the givenh2element using the methodpreceding_nodes. Then, we print eachMojo::DOMobject in a new line by joining the new line,\n, using thejoin()method.