The attr
method is used to find the attributes of HTML elements and interact with them. Interactions with HTML elements may include changing the attribute value or deleting the attribute. This method is provided by the Mojo::DOM
module, which is an HTML/XML DOM parser with CSS selectors.
$dom->attr('attribute');
Where an example of the attribute
is id
.
This method will return the attribute
value if we try to find it. It will return the Mojo::DOM
object if we change the attribute
value.
Let’s look at an example of this:
The given HTML is as follows:
<div>
Inside div
<p id="a">Inside first paragraph </p>
<p id="b">Inside second paragraph</p>
</div>
If we use the attr
method to find the value of the id
attribute for the first descendant element of the given element p
, we will get the following output for the given HTML.
a
use 5.010;use Mojo::DOM;# Parse the htmlmy $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside first paragraph </p><p id="b">Inside second paragraph</p></div>');# Find attribute attribute valuesay $dom->at('p')->attr('id');
Mojo::DOM
module.$dom
scalar.id
for the first descendant of the given element p
. Then, we print the result to the console.