What is the child_nodes method in Mojo::DOM?

Overview

The child_nodes method is used to find all the child nodes for the given element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

It is helpful while fetching the first child node or last child node for the given element.

Syntax

$dom->at('html element')->child_nodes

Return value

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

Example

A sample HTML code is given below.

<div>
Inside div
<p id="a">Inside first paragraph </p>
<p id="b">Inside second paragraph</p>
</div>

If we find the first node for the given element, div, using the child_nodes method, we get the following output:

Inside div

Code example

use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside first paragraph </p><p id="b">Inside second paragraph</p></div>');
# Get first child element
say $dom->at('div')->child_nodes->first;
# Get last child element
say $dom->at('div')->child_nodes->last;

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the scalar $dom.
  • Line 8: We use the child_nodes method to find the first node for the given element div, and print its Mojo::DOM object.
  • Line 11: We use the child_nodes method to find the last node for the given element div, and print its Mojo::DOM object.

    Free Resources