sid_com
sid_com

Reputation: 25117

Mojo::DOM: how does "matches" work?

What do I need to change in the example below, so that the matches( 'a[rel="next"]' ) returns true?

#!/usr/bin/env perl
use warnings;
use strict;
use Mojo::DOM;

my $content = '<html><body><div><a hello="world" rel="next">Next</a></div></body></html>';

my $bool_1 = $content =~ /<a.+?rel="next"/;
print "1 OK\n" if $bool_1;

my $dom = Mojo::DOM->new( $content );
my $bool_2 = $dom->matches( 'a[rel="next"]' );
print "2 OK\n" if $bool_2; # does not print "2 OK"

Upvotes: 0

Views: 63

Answers (1)

BoltClock
BoltClock

Reputation: 723759

The result of Mojo::DOM->new( $content ) is the entire DOM represented by the markup. The starting element is always the top-level element; in this case, it's html. Naturally, html does not match the selector a[rel="next"], and therefore matches() returns false.

You need to navigate to the a element using at() before testing it:

my $dom = Mojo::DOM->new( $content );
my $a = $dom->at( 'a' );
my $bool_2;
if ( defined $a ) {
    $bool_2= $a->matches( 'a[rel="next"]' );
}
print "2 OK\n" if $bool_2;

Upvotes: 1

Related Questions