How do I set a node's attribute with Mojo::DOM?

Viewed 72

I'm trying to set an attribute with Mojo::DOM like so:

use Mojo::DOM;

my $a = Mojo::DOM->new('<a></a>');
my $a = $a->attr({ 'href' => 'https://foo/bar' });
print $a;

I would expect it to print

<a href="https://foo/bar"></a>

but I get

<a></a>

What am I doing wrong?

1 Answers

Need to find and return the element first, for which the attribute gets changed

use warnings;
use strict;
use feature 'say';
use Mojo::DOM;

my $dom = Mojo::DOM->new('<a></a>');

$dom->at('a')->attr({ 'href' => 'https://foo/bar' });

say $dom;

This is needed as there is no "attribute" for the whole tree. As docs say in the beginning

While all node types are represented as Mojo::DOM objects, some methods like attr and namespace only apply to elements.

("elements" being nodes of the type "tag", see the link)

Related