如何使用 Mojo::DOM 设置节点的属性?

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

我正在尝试使用 Mojo::DOM 设置属性,如下所示:

use Mojo::DOM;

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

我希望它能打印

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

但我明白了

<a></a>

我做错了什么?

首先需要find and return元素,其属性被更改

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;

这是必需的,因为整棵树没有 "attribute"。如开头的docs say

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

("elements" 是 "tag" 类型的节点,请参阅 link)