Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mojo
perl
communitycreator

What is the Mojo::DOM ancestors method?

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 ancestors method is used to find the ancestors 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->at('html element')->ancestors

Returns

This method returns Mojo::Collection, which contains ancestor Mojo::DOM objects.

Example

Let’s take a look at an example:

The given HTML is as follows:

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

If we try to find the ancestors of the given element span using the ancestors method. For the given HTML, we’ll get output as follows:

p
div
p and div elements are ancestors of span element

Code

Let’s look at the code below:

use 5.010;
use Mojo::DOM;

# Parse the html
my $dom = Mojo::DOM->new('<div>Inside div <p id="a"><span>Inside first paragraph</span> </p><p id="b">Inside second paragraph</p></div>');

# Find ancestor tags
say $dom->at('span')->ancestors->map('tag')->join("\n");

Explanation

In the code snippet above:

  • Line 2: We import the Mojo::DOM module.
  • Line 5: We parse the HTML and store it in scalar $dom.
  • Line 8: We find the ancestors of element span using the method ancestors, and print their tags.

RELATED TAGS

mojo
perl
communitycreator

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