What is Mojo::DOM prepend_content?

Overview

The method prepend_content is used to prepend the HTML/XML fragment or raw content to the given element’s content. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

$dom->prepend_content('HTML/XML fragment or raw content')

Return value

This method will return the Mojo::DOM object after prepending the given HTML/XML fragment or raw content to the given element.

Let’s look at an example.

Example

<div>
   Inside div
   <p id="a">Inside first paragraph </p>
</div>

When we prepend the HTML fragment <span>New content</span> to the element p using the prepend_content method, we’ll the following output:

<div>
   Inside div 
   <p id="a"><span>New content</span>Inside first paragraph </p>
</div>

Example

use 5.010;
use Mojo::DOM;
# Parse the html
say my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside first paragraph</p></div>');
# Prepend the HTML fragment using prepend_content
say $dom->at('p')->prepend_content('<span>New content</span>')->root

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML, store it in scalar $dom, and display it.
  • In Line 8: We prepend the given HTML fragment to the element p using the prepend_content method, get the root element, and display it.

Note: The method prepend will prepend the HTML fragment before the given element, and the method prepend_content will prepend the HTML fragment before the content of the given element.

Free Resources