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 printTrueif it returns1else printFalsefor better view of the output.
use 5.010;use Mojo::DOM;# Parse the htmlmy $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::DOMmodule. - Line 5: We parse the HTML and store it in the scalar
$dom. - Line 8: We check if the element
pmatches with the given CSS selector#a. - Lines 11–15: We print the output according to the result returned from line 8.