Share
The content
method gets the content for a given element or replaces the content present in the same element. This method is provided by the Mojo::DOM
module, which is an HTML/XML DOM parser with CSS selectors.
We use the following syntax to get the content:
$dom->at('html element')->content
We use the following syntax to replace the content:
$dom->at('html element')->content('new content')
content
: This method returns the given node's content.content('new content')
: This method returns the Mojo::DOM
object after replacing the content with new content.Let’s take a look at an example.
A sample HTML code is given below.
<div>Inside div<p id="a"><span>Inside first paragraph</span> </p><p id="b">Inside second paragraph</p></div>
If we try to get the content for the span
element using the content
method, we get the following output:
Inside first paragraph
use 5.010;use Mojo::DOM;# Parse the HTMLmy $dom = Mojo::DOM->new('<div>Inside div <p id="a"><span>Inside first paragraph</span></p><p id="b">Inside second paragraph</p></div>');# Get the contentsay $dom->at('span')->content
Mojo::DOM
module.$dom
.span
using the content
method.Let's now take a look at how to replace the content for the given element.
use 5.010;use Mojo::DOM;# Parse the HTMLmy $dom = Mojo::DOM->new('<div>Inside div <p id="a"><span>Inside first paragraph</span></p><p id="b">Inside second paragraph</p></div>');# Replace the contentsay $dom->at('div')->content("Replaced content in div")
div
element, and print the Mojo::DOM
object with the new content.