What is the following_nodes method in Mojo::DOM?

Overview

The following_nodes method is used to find the sibling nodes 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 following method returns the sibling elements while the following_nodes method returns the sibling nodes.

Syntax

$dom->following_nodes
following_nodes

Return value

This method returns the Mojo::Collection, which contains each node as a Mojo::DOM object.

Example

A sample HTML code is provided 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 sibling nodes for the given element p using the following_nodes method, we get the following output:

After paragraph
<h1>Inside h1</h1>
<h2>Inside h2</h2>
Output

Code

Let's look at the code below:

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 sibling nodes
say $dom->at('p')->following_nodes->join("\n");

Explanation

In the above code snippet:

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the scalar $dom.
  • Line 8: We get the sibling nodes for the given element p using the method following_nodes and print the returned Mojo::DOM collection.

Free Resources