Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl
communitycreator
mojo

What is the preceding method in Mojo::DOM?

Gutha Vamsi Krishna

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The preceding method is used to find the preceding sibling elements for the given element. This method is provided by the Mojo::DOM module, which is an HTML/XML DOM parser with CSS selectors.

Syntax

$dom->preceding
Syntax of the preceding method

Return value

This method returns the Mojo::Collection, which contains each element as a Mojo::DOM object.

Example

A sample HTML code is given below:

<div>
Inside div
<p id="a">Inside paragraph </p>
After paragraph
<h1>Inside h1</h1>
<h2>Inside h2</h2>
</div>

If we find the preceding siblings for the given element, h2, using the preceding method, we get the following output:

<p id="a">Inside paragraph </p>
<h1>Inside h1</h1>

Code example

use 5.010;
use Mojo::DOM;
# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a">Inside paragraph </p>After paragraph<h1>Inside h1</h1><h2>Inside h2</h2></div>');
# Get preceding siblings
say $dom->at('h2')->preceding->join("\n");
Implementation of Mojo::Dom

Explanation

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in the scalar $dom.
  • Line 8: We use the preceding method to get the preceding sibling elements for the given element p. Next, we print the returned Mojo::DOM collection.

RELATED TAGS

perl
communitycreator
mojo

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring