What is the matches method in Mojo::DOM?

Overview

The matches method is used to check if the element matches the given CSS selector. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

$dom->matches('CSS selector')

Parameters

The method matches accepts a CSS selector as a parameter.

Return value

This method will return 1 if it matches. Otherwise, it will return nothing.

Let’s take a look at an example.

Working example

A sample HTML code is given below.

<div>
Inside div
<p id="a">Inside paragraph </p>
<h1>Inside h1</h1>
<h2>Inside h2</h2>
</div>

If we check whether the element p matches with the given CSS selector #a or not using matches method it will return 1 since it matches, and we will print True.

Note: We will print True if it returns 1 else print False for better view of the output.
use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside paragraph </p><h1>Inside h1</h1><h2>Inside h2</h2></div>');
# Use of matches
$bool = $dom->at('p')->matches('#a');
if($bool){
say "True"
}else{
say "False"
}

Explanation

In the code snippet above, we see the following.

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the scalar $dom.
  • Line 8: We check if the element p matches with the given CSS selector #a.
  • Lines 11–15: We print the output according to the result returned from line 8.

Free Resources