What is the Mojo::DOM module's attr method?
Overview
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.
Syntax
$dom->attr('attribute');
Where an example of the attribute is id.
Return value
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:
Code example
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
Code example
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');
Code explanation
- Line 2: We import the
Mojo::DOMmodule. - Line 5: We parse the HTML and store it in the
$domscalar. - Line 8: We find the attribute value of an attribute
idfor the first descendant of the given elementp. Then, we print the result to the console.