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 html
my $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 value
say $dom->at('p')->attr('id');

Code explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the $dom scalar.
  • Line 8: We find the attribute value of an attribute id for the first descendant of the given element p. Then, we print the result to the console.

Free Resources