HTML::Element(3pm)

πŸ’– HTML::Element(3pm) πŸ’–

okay so this page is from the User Contributed Perl Documentation corner of the universe, and it's about HTML::Element β€” the class that's literally built for objects representing HTML elements. πŸ¦‹

🌸 NAME 🌸

HTML::Element β€” Class for objects that represent HTML elements.

✨ VERSION ✨

This document describes version 5.07 of HTML::Element, released August 31, 2017 as part of HTML-Tree. No cap.

πŸŽ€ SYNOPSIS πŸŽ€

use HTML::Element;
$a = HTML::Element->new('a', href => 'http://www.perl.com/');
$a->push_content("The Perl Homepage");

$tag = $a->tag;
print "$tag starts out as:",  $a->starttag, "\n";
print "$tag ends as:",  $a->endtag, "\n";
print "$tag\'s href attribute is: ",  $a->attr('href'), "\n";

$links_r = $a->extract_links();
print "Hey, I found ", scalar(@$links_r), " links.\n";

print "And that, as HTML, is: ", $a->as_HTML, "\n";
$a = $a->delete;

πŸ¦‹ DESCRIPTION πŸ¦‹

This class is part of the HTML::Tree dist. πŸ’œ

Objects of the HTML::Element class can be used to represent elements of HTML document trees. These objects have attributes, notably attributes that designates each element's parent and content. The content is an array of text segments and other HTML::Element objects. A tree with HTML::Element objects as nodes can represent the syntax tree for a HTML document. 🌳✨

πŸ’… HOW WE REPRESENT TREES πŸ’…

Okay bestie, consider this HTML document:

         <html lang='en-US'>
           <head>
             <title>Stuff</title>
             <meta name='author' content='Jojo'>
           </head>
           <body>
            <h1>I like potatoes!</h1>
           </body>
         </html>

Building a syntax tree out of it makes a tree-structure in memory that could be diagrammed as:

                            html (lang='en-US')
                             / \
                           /     \
                         /         \
                       head        body
                      /\               \
                    /    \               \
                  /        \               \
                title     meta              h1
                 |       (name='author',     |
              "Stuff"    content='Jojo')    "I like potatoes"

This is the traditional way to diagram a tree, with the "root" at the top, and it's this kind of diagram that people have in mind when they say, for example, that "the meta element is under the head element instead of under the body element". (The same is also said with "inside" instead of "under" β€” the use of "inside" makes more sense when you're looking at the HTML source.) 😌

Another way to represent the above tree is with indenting:

         html (attributes: lang='en-US')
           head
             title
               "Stuff"
             meta (attributes: name='author' content='Jojo')
           body
             h1
               "I like potatoes"

Incidentally, diagramming with indenting works much better for very large trees, and is easier for a program to generate. The $tree->dump method uses indentation just that way. ✨

However you diagram the tree, it's stored the same in memory β€” it's a network of objects, each of which has attributes like so:

         element #1:  _tag: 'html'
                      _parent: none
                      _content: [element #2, element #5]
                      lang: 'en-US'

         element #2:  _tag: 'head'
                      _parent: element #1
                      _content: [element #3, element #4]

         element #3:  _tag: 'title'
                      _parent: element #2
                      _content: [text segment "Stuff"]

         element #4   _tag: 'meta'
                      _parent: element #2
                      _content: none
                      name: author
                      content: Jojo

         element #5   _tag: 'body'
                      _parent: element #1
                      _content: [element #6]

         element #6   _tag: 'h1'
                      _parent: element #5
                      _content: [text segment "I like potatoes"]

The "treeness" of the tree-structure that these elements comprise is not an aspect of any particular object, but is emergent from the relatedness attributes (_parent and _content) of these element-objects and from how you use them to get from element to element. 🌳

While you could access the content of a tree by writing code that says "access the 'src' attribute of the root's first child's seventh child's third child", you're more likely to have to scan the contents of a tree, looking for whatever nodes, or kinds of nodes, you want to do something with. The most straightforward way to look over a tree is to "traverse" it; an HTML::Element method ($h->traverse) is provided for this purpose; and several other HTML::Element methods are based on it. πŸ‘‘

(For everything you ever wanted to know about trees, and then some, see Niklaus Wirth's Algorithms + Data Structures = Programs or Donald Knuth's The Art of Computer Programming, Volume 1.) πŸ“š

🧚 Weak References 🧚

TL;DR summary: use HTML::TreeBuilder 5 -weak; and forget about the delete method (except for pruning a node from a tree). πŸ’…

Because HTML::Element stores a reference to the parent element, Perl's reference-count garbage collection doesn't work properly with HTML::Element trees. Starting with version 5.00, HTML::Element uses weak references (if available) to prevent that problem. Weak references were introduced in Perl 5.6.0, but you also need a version of Scalar::Util that provides the weaken function. πŸ”₯

Weak references are enabled by default. If you want to be certain they're in use, you can say use HTML::Element 5 -weak;. You must include the version number; previous versions of HTML::Element ignored the import list entirely. ⭐

To disable weak references, you can say use HTML::Element -noweak;. This is a global setting.

🚨 Deprecated alert: This feature is deprecated and is provided only as a quick fix for broken code. If your code does not work properly with weak references, you should fix it immediately, as weak references may become mandatory in a future version. Generally, all you need to do is keep a reference to the root of the tree until you're done working with it. 😭

Because HTML::TreeBuilder is a subclass of HTML::Element, you can also import -weak or -noweak from HTML::TreeBuilder: e.g. use HTML::TreeBuilder: 5 -weak;. 🫢

πŸ’– BASIC METHODS πŸ’–

Okay bestie, this is where it gets good. These are the everyday, bread-and-butter methods you'll be using constantly β€” no cap. ✨

new

$h = HTML::Element->new('tag', 'attrname' => 'value', ... );

This is the constructor, and it hands you back a shiny new HTML::Element object. πŸŽ€ The tag name is a required argument β€” like, you genuinely cannot skip it β€” and it gets forced to lowercase whether you like it or not. Optionally you can pass in other starting attributes right at creation time. Iconic.

attr

$value = $h->attr('attr');
$old_value = $h->attr('attr', $new_value);

Reads (and optionally sets) the value of the given attribute on $h. The attribute name gets forced to lowercase β€” but not the value, if you gave one. If you try to read an attribute that isn't there on this element, you get undef back. If you're setting a new value, you get the old value returned. πŸ’…

If there's a dedicated method for accessing an attribute (like $h->tag for _tag, or $h->content_list, etc. β€” they're all further down), use that instead of calling $h->attr, whether you're reading or setting.

Heads up bestie: setting an attribute to undef (as opposed to "", the empty string) actually deletes the attribute. Yes, those are different things. Yes, it matters. 😭

tag

$tagname = $h->tag();
$h->tag('tagname');

Returns (and optionally sets) the tag name β€” also known as the generic identifier β€” for the element $h. When setting, the tag name is always converted to lower case.

There are four kinds of "pseudo-elements" that show up as HTML::Element objects:

Comment pseudo-elements

These are element objects whose $h->tag value is ~comment, and the comment's content lives in the text attribute ($h->attr("text")). So like, if you parse this with HTML::TreeBuilder...

<!-- I like Pie.
   Pie is good
-->

...you get an HTML::Element object with these attributes:

"_tag",
"~comment",
"text",
" I like Pie.\n     Pie is good\n  "

Declaration pseudo-elements

Declarations (you'll rarely run into these) show up as HTML::Element objects with a tag name of ~declaration, and the content sits in the text attribute. For example, this:

<!DOCTYPE foo>

produces an element whose attributes include:

"_tag", "~declaration", "text", "DOCTYPE foo"

Processing instruction pseudo-elements

PIs (also rarely encountered, ngl) are represented as HTML::Element objects with a tag name of ~pi, and the content lives in the text attribute. So this:

<?stuff foo?>

produces an element whose attributes include:

"_tag", "~pi", "text", "stuff foo?"

(assuming a recent version of HTML::Parser ✨)

~literal pseudo-elements

These objects aren't currently produced by HTML::TreeBuilder, but you can use them to represent a "super-literal" β€” like, a literal you want to be immune from escaping. (Yes, I just made that term up. πŸ’€)

Point is, this is useful when you want to insert code into a tree that you're planning to dump out with as_HTML, and for some reason you want to suppress as_HTML's normal behaviour of amp-quoting text segments.

For example, this:

my $literal = HTML::Element->new('~literal',
  'text' => 'x < 4 & y > 7'
);
my $span = HTML::Element->new('span');
$span->push_content($literal);
print $span->as_HTML;

prints this:

<span>x < 4 & y > 7</span>

Whereas this:

my $span = HTML::Element->new('span');
$span->push_content('x < 4 & y > 7');
  # normal text segment
print $span->as_HTML;

prints this:

<span>x &lt; 4 &amp; y &gt; 7</span>

Unless you're out here inserting tons of pre-cooked code into existing trees and dumping them back out, it's pretty unlikely you'll find ~literal pseudo-elements useful. πŸ¦‹

parent

$parent = $h->parent();
$h->parent($new_parent);

Returns (and optionally sets) the parent β€” aka the "container" β€” for this element. The parent should either be undef, or another element.

Please don't use this to directly set an element's parent, bestie. Use any of the other methods under "Structure-Modifying Methods" below instead. πŸ™ˆ

Also good to know: not($h->parent) is a super simple test for whether $h is the root of its subtree. πŸŽ€

content_list

@content = $h->content_list();
$num_children = $h->content_list();

Returns a list of the child nodes of this element β€” meaning, what nodes (elements or text segments) are inside/under this element. (And yes, this may totally be an empty list.)

In a scalar context, this gives you the count of items, just like you'd expect. πŸ’…

content

$content_array_ref = $h->content(); # may return undef

This somewhat deprecated method returns the content of this element β€” but unlike content_list, it returns either undef (which you should read as "no content"), or a reference to the array of content items, each of which is either a text segment (a string, i.e. a defined non-reference scalar value) or an HTML::Element object. And note: even if an arrayref comes back, it may be a reference to an empty array.

Older code can feel free to keep using $h->content, but new code should use $h->content_list in almost all conceivable cases. Honestly in my experience that leads to simpler code anyway, since you can just say:

@children = $h->content_list;

instead of the inelegant:

@children = @{$h->content || []};
If you do use $h->content (or $h->content_array_ref), do not use the reference it returns (assuming it returned a reference and not undef) to directly set or change the content of an element or text segment! Use content_refs_list or any of the other methods under "Structure-Modifying Methods" below instead. 😀

content_array_ref

$content_array_ref = $h->content_array_ref(); # never undef

This is like content (with all its caveats and deprecations) except it's guaranteed to return an array reference. So like, if the given node has no _content attribute, the content method would return that undef β€” but content_array_ref sets the given node's _content value to [] (a reference to a new, empty array) and returns that. Slay. ✨

content_refs_list

@content_refs = $h->content_refs_list;

Returns a list of scalar references to each element of $h's content list. This is useful when you want to in-place edit a large text segment without having to grab a copy of its current value, modify the copy, then use splice_content to swap the old for the new. Instead, you can just edit in place:

foreach my $item_r ($h->content_refs_list) {
    next if ref $$item_r;
    $$item_r =~ s/honour/honor/g;
}

You could currently get the same effect with:

foreach my $item (@{ $h->content_array_ref }) {
    # deprecated!
    next if ref $item;
    $item =~ s/honour/honor/g;
}

...except that using the return value of $h->content or $h->content_array_ref to do that is deprecated, and might just stop working in the future. So like, don't. πŸ’€

implicit

$is_implicit = $h->implicit();
$h->implicit($make_implicit);

Returns (and optionally sets) the _implicit attribute. This attribute is a flag used to indicate that the element wasn't originally present in the source, but got added to the parse tree (by HTML::TreeBuilder, for example) to conform to the rules of HTML structure. πŸŽ€

pos

$pos = $h->pos();
$h->pos($element);

Returns (and optionally sets) the _pos (for "current position") pointer of $h. This attribute is a pointer used during some parsing operations, whose value is whatever HTML::Element element at or under $h is currently "open" β€” like, where $h->insert_element(NEW) will actually insert a new element.

(Tiny thing: this has absolutely nothing to do with the Perl function called pos, the one that controls where regular expression matching starts. Different vibes entirely. πŸ’…)

If you set $h->pos($element), be sure that $element is either $h or an element under $h.

If you've been modifying the tree under $h and you're no longer sure $h->pos is valid, you can force it to be valid with:

$h->pos(undef) unless $h->pos->is_inside($h);

all_attr

%attr = $h->all_attr();

Returns all of this element's attributes and values as key-value pairs. This will include any "internal" attributes β€” i.e., ones that weren't present in the original element, and which won't be represented if/when you call $h->as_HTML. Internal attributes are distinguished by the fact that the first character of their key (not value! key!) is an underscore (_).

Example output of $h->all_attr() : '_parent', "[object_value]" , '_tag', 'em', 'lang', 'en-US', '_content', "[array-ref value].

all_attr_names

@names = $h->all_attr_names();
$num_attrs = $h->all_attr_names();

Like all_attr, but only returns the names of the attributes. In scalar context, returns the number of attributes.

Example output of $h->all_attr_names() : '_parent', '_tag', 'lang', '_content', .

all_external_attr

%attr = $h->all_external_attr();

Like all_attr, except internal attributes aren't present. πŸ¦‹

all_external_attr_names

@names = $h->all_external_attr_names();
$num_attrs = $h->all_external_attr_names();

Like all_attr_names, except internal attributes' names aren't present (or counted). 🌸

id

$id = $h->id();
$h->id($string);

Returns (and optionally sets to $string) the id attribute. $h->id(undef) deletes the id attribute.

$h->id(...) is basically equivalent to $h->attr('id', ...), except that when setting the attribute, this method returns the new value, not the old one. Sneaky little difference, but it matters. ✨

idf

$id = $h->idf();
$h->idf($string);

Just like the id method, except that if you call $h->idf() and no id attribute is defined for this element, then it gets set to a likely-to-be-unique value and returned to you. (The "f" stands for "force", iykyk. πŸ’…)

πŸ› οΈ STRUCTURE-MODIFYING METHODS πŸ› οΈ

Okay bestie, these are the methods that let you actually change stuff β€” like, you can add nodes, swap nodes, yeet nodes out of the tree. Think of it as interior design but for your tree's parents-and-children sitch. No cap, this is where things get fun. πŸ’…


πŸ“₯ push_content

$h->push_content($element_or_text, ...);

Adds the stuff you give it to the end of $h's content list. Every item you pass in should be one of these three things: a text segment (just a string, bestie), an HTML::Element object, or an arrayref. And arrayrefs? They get fed thru $h->new_from_lol(that_arrayref) first, which turns them into elements, before they get added to $h's content list. Which means you can write cosy little concise things like this:

$body->push_content(
  ['br'],
  ['ul',
    map ['li', $_], qw(Peaches Apples Pears Mangos)
  ]
);

If you want the full explanation, the "new_from_lol" method's docs are way down below. πŸ’–

Returns $h β€” the element itself. She's giving self-returning queen energy.

🫢 Heads up, this next bit is important! push_content tries to consolidate adjacent text segments while it's adding to the content list. So if $h's "content_list" is:
('foo bar ', $some_node, 'baz!')

and you call:

$h->push_content('quack?');

then the resulting content list is gonna be this:

('foo bar ', $some_node, 'baz!quack?')

and not this:

('foo bar ', $some_node, 'baz!', 'quack?')

If the second one is genuinely what you wanted (no judgement), you gotta override the consolidate-those-text-segments feature by using splice_content instead, like so:

$h->splice_content(scalar($h->content_list),0,'quack?');

Same energy on the other end, btw. If you wanted to add 'Skronk' to the beginning of the content list, and you call this:

$h->unshift_content('Skronk');

then you get:

('Skronkfoo bar ', $some_node, 'baz!')

and not:

('Skronk', 'foo bar ', $some_node, 'baz!')

To get that second one, do this:

$h->splice_content(0,0,'Skronk');

πŸ“€ unshift_content

$h->unshift_content($element_or_text, ...)

Literally just like "push_content" but it adds to the beginning of $h's content list instead. ✨

The items should each be a text segment (string), an HTML::Element object, or an arrayref (which gets fed thru "new_from_lol", same as before).

And yes, unshift_content also tries to consolidate adjacent text segments while adding β€” scroll up for the whole discussion on that, it's the exact same deal. πŸŒ€

Returns $h (the element itself, again, icon behaviour).

βœ‚οΈ splice_content

@removed = $h->splice_content($offset, $length,
                              $element_or_text, ...);

Detaches elements from $h's content-node list β€” starting at $offset and going for $length items β€” and replaces them with the elements of the list that follows, if there are any. Returns the elements that got removed (if any). 🌸

If $offset is negative, it starts that far from the end of the array, exactly like Perl's normal "splice" function. And if $length and the following list are both omitted, it removes everything from $offset onward. Bye bestie. πŸ‘‹

The items being added (if any) should each be a text segment (string), an arrayref (fed thru "new_from_lol"), or an HTML::Element object that's not already a child of $h.

πŸ•ŠοΈ detach

$old_parent = $h->detach();

Unlinks $h from its parent β€” sets its 'parent' attribute to undef, and removes it from its parent's content list (if it had one). The return value is the parent it got detached from (or undef, if $h had no parent to begin with). πŸ™ˆ

πŸ’€ Careful, bestie: neither $h nor its parent get explicitly destroyed here. They just... stop talking to each other. It's giving mutual unfollow.

🧺 detach_content

@old_content = $h->detach_content();

Unlinks all of $h's children from $h and returns them. Again: these are not explicitly destroyed. If that's what you want, just use "$h->delete_content" β€” she'll handle the full demolition. πŸ”₯

πŸ” replace_with

$h->replace_with( $element_or_text, ... )

Replaces $h in its parent's content list with the nodes you specify. The element $h gets returned (and by then it may have no parent β€” glow up via relocation ✨).

😭 This throws a fatal error if $h has no parent. Can't replace something that isn't plugged in, bestie.

The list of nodes you insert may contain $h, but at most once. Aside from that possible exception, the nodes you're inserting should not already be children of $h's parent.

Also note: this method does not destroy $h if weak references are turned off β€” if you need that, use "$h->replace_with(...)->delete". πŸ’…

⬅️ preinsert

$h->preinsert($element_or_text...);

Inserts the given nodes right BEFORE $h in $h's parent's content list.

πŸ’€ Fatal error if $h has no parent. And none of the given nodes should be $h or other children of $h.

Returns $h.

➑️ postinsert

$h->postinsert($element_or_text...)

Inserts the given nodes right AFTER $h in $h's parent's content list. Mirror image of the one above, same rules apply. πŸͺž

πŸ’€ Also a fatal error if $h has no parent. Also you shouldn't pass in $h itself or other children of $h.

Returns $h.

πŸ«— replace_with_content

$h->replace_with_content();

Replaces $h in its parent's content list with its own content. The element $h gets returned (and by then it has no parent or content of its own β€” she's empty, she's free, she's thriving πŸ¦‹).

😭 Fatal error if $h has no parent. And heads up: this does not destroy $h if weak references are turned off β€” use "$h->replace_with_content->delete" if that's the vibe you need.

πŸ—‘οΈ delete_content

$h->delete_content();
$h->destroy_content(); # alias

Clears the content of $h, calling "$h->delete" on each content element. Compare that with "$h->detach_content" β€” detach just unlinks, delete_content goes full scorched earth. πŸ”₯

Returns $h.

"destroy_content" is an alias for this method. πŸŽ€

☠️ delete

$h->delete();
$h->destroy(); # alias

Detaches this element from its parent (if it's got one) and explicitly destroys the element and every single one of its descendants. The return value is the empty list (or "undef" in scalar context). She's gone, gone. πŸ’€

🌈 History moment, bestie: before version 5.00 of HTML::Element, you had to call "delete" when you were done with the tree, or your program would leak memory. That's no longer necessary if weak references are enabled β€” see "Weak References". Slay, progress.

☠️ destroy

An alias for "delete". Same energy, shorter word. πŸ’…

☠️ destroy_content

An alias for "delete_content". ✨

🧬 clone

$copy = $h->clone();

Returns a copy of the element β€” and its children are clones (recursively) of the original's children, if it had any. It's giving identical twin, no cap. πŸ‘―β€β™€οΈ

The returned element is parentless. Any '_pos' attributes present in the source element/tree will be absent in the copy. And for that reason plus others, if you clone an HTML::TreeBuilder object that's mid-parse (i.e., the head of a tree that HTML::TreeBuilder is currently elaborating), that clone cannot (currently) be used to continue the parse. πŸ™ˆ

You are totally free to clone HTML::TreeBuilder trees, just as long as: 1) they're done being parsed, or 2) you don't expect to resume parsing into the clone. (You can keep parsing into the original β€” it is never affected. She doesn't even notice. πŸ’β€β™€οΈ)

πŸ‘― clone_list

@copies = HTML::Element->clone_list(...nodes...);

Returns a list made of a copy of each node you give it. Text segments are simply copied; elements get cloned by calling "$it->clone" on each one. 🧬

⚠️ Note that this must be called as a class method, not as an instance method. "clone_list" will croak if you call it as an instance method. Rude? Maybe. Enforced? Absolutely.

You can also call it like this:

ref($h)->clone_list(...nodes...)

🧹 normalize_content

$h->normalize_content

Normalizes the content of $h β€” i.e., concatenates any adjacent text nodes. (Any undefined text segments get turned into empty-strings.) ✨

🫢 Note that this does not recurse into $h's descendants. It's a shallow clean, bestie, not a deep one.

🧽 delete_ignorable_whitespace

$h->delete_ignorable_whitespace()

Traverses under $h and deletes any text segments that are ignorable whitespace. Poof, gone, tidy. 🌸

πŸ’€ Do not use this if $h is under a "<pre>" element. Whitespace matters in there! That's the whole point of <pre>!

πŸ“Œ insert_element

$h->insert_element($element, $implicit);

Inserts (via push_content) a new element under the element at "$h->pos()". Then it updates "$h->pos()" to point to the inserted element β€” unless $element is a prototypically empty element like "<br>", "<hr>", "<img>", etc. The new "$h->pos()" gets returned. 🎯

πŸ’… Real talk: this method is useful only if your particular tree task involves setting "$h->pos()". If you're not playing with pos, you can skip her.

πŸ’– DUMPING METHODS πŸ’–

dump

$h->dump()
$h->dump(*FH)  ; # or *FH{IO} or $fh_obj

Prints the element and all its children to STDOUT (or to a filehandle if you hand it one), in a format that is useful only for debugging β€” like, do not ship this, bestie 😭. The document structure shows up via indentation, and there are no end tags. It's giving "quick peek under the hood" energy and nothing more 🫢.


as_HTML

$s = $h->as_HTML();
$s = $h->as_HTML($entities);
$s = $h->as_HTML($entities, $indent_char);
$s = $h->as_HTML($entities, $indent_char, \%optional_end_tags);

Returns a string that represents the element and all its descendants in HTML ✨.

The optional $entities argument is a string of the entities you wanna encode. For compatibility with previous versions, specify '<>&' right there. If you omit it or it's undef, all unsafe characters get encoded as HTML entities. Peep HTML::Entities for the details πŸ’…. If you pass an empty string, then no entities are encoded β€” zero, none, nada.

If $indent_char is specified and defined, the HTML that's output gets indented using the string you gave (and like, you probably want to set it to "\t", or some number of spaces, if you're specifying it at all πŸŽ€).

If \%optional_end_tags is specified and defined, it should be a reference to a hash that holds a true value for every tag name whose end tag is optional. It defaults to \%HTML::Element::optionalEndTag, which is an alias to %HTML::Tagset::optionalEndTag, which, at time of writing, contains true values for "p, li, dt, dd". A genuinely useful value to pass is an empty hashref, {}, which means no end-tags are optional for this dump. Otherwise, maybe consider copying %HTML::Tagset::optionalEndTag into a hash of your own, adding or deleting values as you like, and passing a reference to that hash πŸ¦‹.


as_text

$s = $h->as_text();
$s = $h->as_text(skip_dels => 1);

Returns a string made up of only the text parts of the element's descendants. Any whitespace inside the element is included unchanged, but whitespace that isn't in the tree is never added. That said β€” plot twist β€” whitespace may be ignored or compacted by HTML::TreeBuilder during parsing (depending on the value of the "ignore_ignorable_whitespace" and "no_space_compacting" attributes πŸ™ˆ). And since whitespace is never added during parsing:

HTML::TreeBuilder->new_from_content("<p>a</p><p>b</p>")
                 ->as_text;

returns "ab", not "a b" and not "a\nb". The way that just… does that 😭.

Text under <script> or <style> elements is never included in what's returned. And if "skip_dels" is true, then text content under <del> nodes isn't included either ✨.


as_trimmed_text

$s = $h->as_trimmed_text(...);
$s = $h->as_trimmed_text(extra_chars => '\xA0'); # remove &nbsp;
$s = $h->as_text_trimmed(...); # alias

This is literally just like as_text(...) except leading and trailing whitespace is deleted, and any internal whitespace is collapsed πŸ‘‘.

It will not remove non-breaking spaces, Unicode spaces, or any other non-ASCII whitespace unless you supply the extra characters as a string argument (e.g. "$h->as_trimmed_text(extra_chars => '\xA0')"). "extra_chars" can be any string that can appear inside a character class β€” including ranges like "a-z", POSIX character classes like "[:alpha:]", and character class escapes like "\p{Zs}" 🧚.


as_XML

$s = $h->as_XML()

Returns a string representing the element and its descendants in XML.

The XML is not indented. That's it. That's the whole vibe 🌸.


as_Lisp_form

$s = $h->as_Lisp_form();

Returns a string representing the element and its descendants as a Lisp form. Unsafe characters get encoded as octal escapes πŸ”₯.

The Lisp form is indented, and it contains external attributes ("href", etc.) as well as internal attributes ("_tag", "_content", "_implicit", etc.), except for "_parent", which is omitted πŸ’€.

Current example output for a given element:

("_tag" "img" "border" "0" "src" "pie.png" "usemap" "#main.map")

format

$s = $h->format; # use HTML::FormatText
$s = $h->format($formatter);

Formats text output 🌈. Defaults to HTML::FormatText.

Takes a second argument that's a reference to a formatter πŸŽ€.


starttag

$start = $h->starttag();
$start = $h->starttag($entities);

Returns a string representing the complete start tag for the element β€” like, leading "<", the tag name, the attributes, and trailing ">" ✨. All values get surrounded with double-quotes, and the appropriate characters are encoded. If $entities is omitted or undef, all unsafe characters are encoded as HTML entities (see HTML::Entities for the deets). If you specify some value for $entities, remember to include the double-quote character in it β€” previous versions of this module would basically behave as if '&">' were specified for $entities, jsyk 😭. And if $entities is an empty string, no entity is escaped.


starttag_XML

$start = $h->starttag_XML();

Returns a string representing the complete start tag for the element πŸ’œ.


endtag

$end = $h->endtag();

Returns a string representing the complete end tag for this element. I.e., "</", the tag name, and ">" πŸ¦‹.


endtag_XML

$end = $h->endtag_XML();

Returns a string representing the complete end tag for this element. I.e., "</", the tag name, and ">" πŸ’…. (Yes bestie, same description as endtag β€” the XML one just gets its own little moment ✨.)


πŸ¦‹ SECONDARY STRUCTURAL METHODS πŸ¦‹

These methods all involve some structural aspect of the tree β€” either they report some aspect of the tree's structure, or they involve traversal down the tree, or walking up the tree 🧚. It's giving tree gossip, ngl.


is_inside

$inside = $h->is_inside('tag', $element, ...);

Returns true if the $h element is, or is contained anywhere inside, an element that's any of the ones listed, or whose tag name is any of the tag names listed πŸ‘‘. And you can use any mix of elements and tag names β€” go off, honestly 🌈.


is_empty

$empty = $h->is_empty();

Returns true if $h has no content β€” i.e., has no elements or text segments under it. In other words, this returns true if $h is a leaf node, AKA a terminal node πŸ“.

⚠️ Do not confuse this sense of "empty" with another sense it can have in SGML/HTML/XML terminology, which means that the element in question is of the type (like HTML's <hr>, <br>, <img>, etc.) that can't have any content. That is, a particular <p> element may happen to have no content, so $that_p_element->is_empty will be true β€” even though the prototypical <p> element isn't "empty" (not in the way that the prototypical <hr> element is) 😭.

If you think this might make for potentially confusing code, consider just using the clearer exact equivalent: not($h->content_list) β€” same thing, way less "wait, what?" energy πŸ’€.


pindex

$index = $h->pindex();

Returns the index of the element in its parent's contents array, such that $h would equal:

$h->parent->content->[$h->pindex]
# or
($h->parent->content_list)[$h->pindex]

…assuming $h isn't root 🫢. If the element $h is root, then "$h->pindex" returns "undef" πŸ™ˆ.


left

$element = $h->left();
@elements = $h->left();

In scalar context: returns the node that's the immediate left sibling of $h ✨. If $h is the leftmost (or only) child of its parent (or has no parent at all), then this returns undef 😭.

In list context: returns all the nodes that're the left siblings of $h (starting with the leftmost). If $h is the leftmost (or only) child of its parent (or has no parent), then this returns an empty list.

(See also "$h->preinsert(LIST)".) πŸ’œ


$element = $h->right();
@elements = $h->right();

In scalar context: returns the node that's the immediate right sibling of $h ✨. If $h is the rightmost (or only) child of its parent (or has no parent), then this returns "undef" 😭.

In list context: returns all the nodes that're the right siblings of $h, starting with the leftmost. If $h is the rightmost (or only) child of its parent (or has no parent), then this returns an empty list.

(See also "$h->postinsert(LIST)".) πŸ’œ


address

$address = $h->address();
$element_or_text = $h->address($address);

The first form (with no parameter) returns a string representing the location of $h in the tree it's a member of 🌸. The address is numbers joined by a ., starting with '0', and followed by the pindexes of the nodes in the tree that are ancestors of $h, starting from the top πŸ‘‘

So if the way to get to a node starting at the root is to go to child 2 of the root, then child 10 of that, and then child 0 of that, and then you're there β€” then that node's address is "0.2.10.0" ✨.

As a bit of a special case, the address of the root is simply "0" πŸŽ€.

I forsee this being used mainly for debugging, but you may find your own uses for it 🫢.

$element_or_text = $h->address($address);

This form returns the node (whether element or text-segment) at the given address in the tree that $h is a part of. (That is, the address is resolved starting from "$h->root".) πŸ’…

If there's no node at the given address, this returns "undef" πŸ’€.

You can specify "relative addressing" (i.e., that indexing is supposed to start from $h and not from "$h->root") by having the address start with a period β€” e.g., "$h->address(".3.2")" will look at child 3 of $h, and child 2 of that πŸ¦‹.


depth

$depth = $h->depth();

Returns a number expressing $h's depth within its tree, i.e., how many steps away it is from the root 🌈. If $h has no parent (i.e., is root), its depth is 0 ✨.


root

$root = $h->root();

Returns the element that's the top of $h's tree πŸ‘‘. If $h is root, this just returns $h. (If you wanna test whether $h is the root, instead of asking what its root is, just test not($h->parent) β€” way simpler, bestie πŸ’….)


lineage

@lineage = $h->lineage();

Returns the list of $h's ancestors, starting with its parent, and then that parent's parent, and so on, up to the root 🌸. If $h is root, this returns an empty list.

If you simply want a count of the number of elements in $h's lineage, use "$h->depth" β€” built different, honestly ✨.


lineage_tag_names

@names = $h->lineage_tag_names();

Returns the list of the tag names of $h's ancestors, starting with its parent, and that parent's parent, and so on, up to the root πŸŽ€. If $h is root, this returns an empty list. Example output: ('em', 'td', 'tr', 'table', 'body', 'html') πŸ‘‘

Equivalent to:

map { $_->tag } $h->lineage;

descendants

@descendants = $h->descendants();

In list context, returns the list of all $h's descendant elements, listed in pre-order (i.e., an element appears before its content-elements) 🌈. Text segments DO NOT appear in the list πŸ’€. In scalar context, returns a count of all such elements ✨.


descendents

This is just an alias to the "descendants" method, for people who can't spell 😭🫢. No shade β€” we've all been there.


find_by_tag_name

@elements = $h->find_by_tag_name('tag', ...);
$first_match = $h->find_by_tag_name('tag', ...);

In list context, returns a list of elements at or under $h that have any of the specified tag names πŸ‘‘. In scalar context, returns the first (in pre-order traversal of the tree) such element found, or undef if there's none 🌸.

find

Okay so find is literally just an alias to find_by_tag_name, bestie. That's it, that's the whole method. πŸŽ€

The lore tho: there was once gonna be a whole find_* family of methods, but then look_down swooped in and filled that niche, so there turned out to not be much reason for the verboseness of the name find_by_tag_name. Iconic honestly. πŸ’…


find_by_attribute

@elements = $h->find_by_attribute('attribute', 'value');
$first_match = $h->find_by_attribute('attribute', 'value');

In list context, it hands you a list of elements at or under $h that have the specified attribute and have the given value for that attribute. In scalar context, you get the first one found (in pre-order traversal of the tree), or undef if none. πŸ¦‹

Heads up bestie β€” this method is deprecated in favor of the more expressive look_down method, and new code should use that instead. No cap, find_by_attribute is giving legacy energy. 😭

look_down

@elements = $h->look_down( ...criteria... );
$first_match = $h->look_down( ...criteria... );

This starts at $h and looks thru its element descendants (in pre-order), searching for elements matching the criteria you specify. In list context, it returns all elements that match all the given criteria; in scalar context, it returns the first such element (or undef, if nothing matched). 🌈

There are three kinds of criteria you can specify β€” memorize these, they're the whole vibe:

  • (attr_name, attr_value) β€” this means you're looking for an element with that value for that attribute. Example: "alt", "pix!". And consider that you can search on internal attribute values too: "_tag", "p". 🫢
  • (attr_name, qr/.../) β€” this means you're looking for an element whose value for that attribute matches the specified Regexp object. Regex girlies rise. ✨
  • a coderef β€” this means you're looking for elements where coderef->(each_element) returns true. Example:
my @wide_pix_images = $h->look_down(
  _tag => "img",
  alt  => "pix!",
  sub { $_[0]->attr('width') > 350 }
);

Note that (attr_name, attr_value) and (attr_name, qr/.../) criteria are almost always faster than coderef criteria, so you should presumably put them before the coderefs in your list of criteria. That is, in the example above, the sub ref is called only for elements that have already passed the criteria of having a "_tag" attribute with value "img", and an "alt" attribute with value "pix!". If the coderef were first, it would be called on every single element, and then whatever elements pass that criterion (i.e., elements for which the coderef returned true) would be checked for their "_tag" and "alt" attributes. Efficiency queen behavior. πŸ‘‘

Note that comparison of string attribute-values against the string value in (attr_name, attr_value) is case-INsensitive! A criterion of ('align', 'right') will match an element whose "align" value is "RIGHT", or "right" or "rIGhT", etc. It does not care about your capitalization choices. πŸ’€

Note also that look_down considers "" (empty-string) and undef to be different things, in attribute values. So this:

$h->look_down("alt", "")

will find elements with an "alt" attribute, but where the value for the "alt" attribute is "". But this:

$h->look_down("alt", undef)

is the same as:

$h->look_down(sub { !defined($_[0]->attr('alt')) } )

That is, it finds elements that do not have an "alt" attribute at all (or that do have an "alt" attribute, but with a value of undef β€” which is not normally possible). Different vibes entirely, bestie. πŸ™ˆ

Note that when you give several criteria, this is taken to mean you're looking for elements that match all your criteria, not just any of them. In other words, there is an implicit and, not an or. So if you wanted to express that you wanted to find elements with a "name" attribute with the value "foo" or with an "id" attribute with the value "baz", you'd have to do it like:

@them = $h->look_down(
  sub {
    # the lcs are to fold case
    lc($_[0]->attr('name')) eq 'foo'
    or lc($_[0]->attr('id')) eq 'baz'
  }
);

Coderef criteria are more expressive than (attr_name, attr_value) and (attr_name, qr/.../) criteria, and all (attr_name, attr_value) and (attr_name, qr/.../) criteria could be expressed in terms of coderefs. However, (attr_name, attr_value) and (attr_name, qr/.../) criteria are a convenient shorthand. (In fact, look_down itself is basically "shorthand" too, since anything you can do with look_down you could do by traversing the tree, either with the traverse method or with a routine of your own. However, look_down often makes for very concise and clear code.) It's giving convenience store but make it tree traversal. πŸ“


look_up

@elements = $h->look_up( ...criteria... );
$first_match = $h->look_up( ...criteria... );

This is identical to $h->look_down, except that whereas $h->look_down basically scans over the list:

($h, $h->descendants)

$h->look_up instead scans over the list:

($h, $h->lineage)

So it's the upward version, bestie β€” same energy, opposite direction. So, for example, this returns all ancestors of $h (possibly including $h itself) that are <td> elements with an "align" attribute with a value of "right" (or "RIGHT", etc.):

$h->look_up("_tag", "td", "align", "right");

traverse

$h->traverse(...options...)

Lengthy discussion of HTML::Element's unnecessary and confusing traverse method has been moved to a separate file: HTML::Element::traverse. Yes bestie, it got its own whole file. It's that complicated. 😭 Go read that one, this page is not the place.


attr_get_i

@values = $h->attr_get_i('attribute');
$first_value = $h->attr_get_i('attribute');

In list context, returns a list consisting of the values of the given attribute for $h and for all its ancestors starting from $h and working its way up. Nodes with no such attribute are skipped. (attr_get_i stands for "attribute get, with inheritance" β€” iykyk. 🧚)

In scalar context, returns the first such value, or undef if none. πŸ’œ

Consider a document consisting of:

<html lang='i-klingon'>
  <head><title>Pati Pata</title></head>
  <body>
    <h1 lang='la'>Stuff</h1>
    <p lang='es-MX' align='center'>
      Foo bar baz <cite>Quux</cite>.
    </p>
    <p>Hooboy.</p>
  </body>
</html>

If $h is the <cite> element, $h->attr_get_i("lang") in list context will return the list ('es-MX', 'i-klingon'). In scalar context, it will return the value 'es-MX'.

If you call with multiple attribute names...

@values = $h->attr_get_i('a1', 'a2', 'a3');
$first_value = $h->attr_get_i('a1', 'a2', 'a3');

...in list context, this will return a list consisting of the values of these attributes which exist in $h and its ancestors. In scalar context, this returns the first value (i.e., the value of the first existing attribute from the first element that has any of the attributes listed). So, in the above example,

$h->attr_get_i('lang', 'align');

will return:

('es-MX', 'center', 'i-klingon') # in list context
or
'es-MX' # in scalar context.

But note that this:

$h->attr_get_i('align', 'lang');

will return:

('center', 'es-MX', 'i-klingon') # in list context
or
'center' # in scalar context.

Order matters, bestie! The order you list the attribute names totally changes the output. ⭐


tagname_map

$hash_ref = $h->tagname_map();

Scans across $h and all its descendants, and makes a hash (a reference to which is returned) where each entry consists of a key that's a tag name, and a value that's a reference to a list of all elements that have that tag name. I.e., this method returns:

{
  # Across $h and all descendants...
  'a'   => [ ...list of all <a>   elements... ],
  'em'  => [ ...list of all <em>  elements... ],
  'img' => [ ...list of all <img> elements... ],
}

(There are entries in the hash for only those tagnames that occur at/under $h β€” so if there's no <img> elements, there'll be no img entry in the returned hashref. No empty little ghosts haunting your hash. πŸ‘»)

Example usage:

my $map_r = $h->tagname_map();
my @heading_tags = sort grep m/^h\d$/s, keys %$map_r;
if(@heading_tags) {
  print "Heading levels used: @heading_tags\n";
} else {
  print "No headings.\n"
}

$links_array_ref = $h->extract_links();
$links_array_ref = $h->extract_links(@wantedTypes);

Returns links found by traversing the element and all of its children and looking for attributes (like "href" in an <a> element, or "src" in an <img> element) whose values represent links. The return value is a reference to an array. Each element of the array is a reference to an array with four items: the link-value, the element that has the attribute with that link-value, and the name of that attribute, and the tagname of that element. (Example: ['http://www.suck.com/', $elem_obj , 'href', 'a'].) You may or may not end up using the element itself β€” for some purposes, you may use only the link value. πŸ¦‹

You might specify that you want to extract links from just some kinds of elements (instead of the default, which is to extract links from all the kinds of elements known to have attributes whose values represent links). For instance, if you want to extract links from only <a> and <img> elements, you could code it like this:

for (@{  $e->extract_links('a', 'img')  }) {
    my($link, $element, $attr, $tag) = @$_;
    print
      "Hey, there's a $tag that links to ",
      $link, ", in its $attr attribute, at ",
      $element->address(), ".\n";
}

simplify_pres

$h->simplify_pres();

In text bits under PRE elements that are at/under $h, this routine nativizes all newlines, and expands all tabs. Cleanup era. 🧹

That is, if you read a file with lines delimited by "\cm\cj"'s, the text under PRE areas will have "\cm\cj"'s instead of "\n"'s. Calling $h->simplify_pres on such a tree will turn "\cm\cj"'s into "\n"'s. Slay, normalization. ✨

Tabs are expanded to however many spaces it takes to get to the next 8th column β€” the usual way of expanding them.


same_as

$equal = $h->same_as($i)

Returns true if $h and $i are both elements representing the same tree of elements, each with the same tag name, with the same explicit attributes (i.e., not counting attributes whose names start with "_"), and with the same content (textual, comments, etc.). Deep comparison, no cap. πŸ’…

Sameness of descendant elements is tested, recursively, with $child1->same_as($child_2), and sameness of text segments is tested with $segment1 eq $segment2. It's turtles all the way down, bestie. 🐒


new_from_lol

$h = HTML::Element->new_from_lol($array_ref);
@elements = HTML::Element->new_from_lol($array_ref, ...);

Recursively constructs a tree of nodes, based on the (non-cyclic) data structure represented by each $array_ref, where that is a reference to an array of arrays (of arrays (of arrays (etc.))). It's arrays inception and honestly it ate. πŸ”₯

In each arrayref in that structure, different kinds of values are treated as follows:

  • Arrayrefs β€” Arrayrefs are considered to designate a sub-tree representing children for the node constructed from the current arrayref.
  • Hashrefs
  • Hashrefs β€” a hashref is read as attribute-value pairs to slap onto the element being built from the arrayref you're currently in. ✨
  • Text segments β€” text at the start of any arrayref is taken as the name of the element being constructed from that arrayref. Every other text segment in there is taken as text-segment children for the current arrayref. πŸŽ€
  • Elements β€” existing element objects either get inserted into the treelet being built, or a clone of them does. Concretely: while the lol-tree is being walked and stuff is being constructed from it, if an existing element object turns up and it has no parent, it gets added straight into the treelet; but if it has a parent, then $that_node->clone is what gets added to the treelet in the right spot. πŸ¦‹

An example makes this way more obvious, fr:

my $h = HTML::Element->new_from_lol(
  ['html',
    ['head',
      [ 'title', 'I like stuff!' ],
    ],
    ['body',
      {'lang', 'en-JP', _implicit => 1},
      'stuff',
      ['p', 'um, p < 4!', {'class' => 'par123'}],
      ['div', {foo => 'bar'}, '123'],
    ]
  ]
);
$h->dump;

That prints this, no cap:

<html> @0
  <head> @0.0
    <title> @0.0.0
      "I like stuff!"
  <body lang="en-JP"> @0.1 (IMPLICIT)
    "stuff"
    <p class="par123"> @0.1.1
      "um, p < 4!"
    <div foo="bar"> @0.1.2
      "123"

And printing $h->as_HTML gives you something like:

<html><head><title>I like stuff!</title></head>
<body lang="en-JP">stuff<p class="par123">um, p &lt; 4!
<div foo="bar">123</div></body></html>

You can even do fancy lil things with map, bestie πŸ‘‘:

$body->push_content(
  # push_content implicitly calls new_from_lol on arrayrefs...
  ['br'],
  ['blockquote',
    ['h2', 'Pictures!'],
    map ['p', $_],
    $body2->look_down("_tag", "img"),
      # images, to be copied from that other tree.
  ],
  # and more stuff:
  ['ul',
    map ['li', ['a', {'href'=>"$_.png"}, $_ ] ],
    qw(Peaches Apples Pears Mangos)
  ],
);

In scalar context you must supply exactly one arrayref. In list context you can pass a whole list of arrayrefs, and new_from_lol returns a list of elements, one for each arrayref. 🫢

@elements = HTML::Element->new_from_lol(
  ['hr'],
  ['p', 'And there, on the door, was a hook!'],
);
 # constructs two elements.

✨ objectify_text ✨

$h->objectify_text();

This turns any text nodes under $h from mere text segments (strings) into real objects β€” pseudo-elements with a tag-name of ~text, and the actual text content sitting in an attribute called text. (Want the whole pseudo-element discussion? It's in the tag method, way up above. πŸ‘†)

Why does this exist? Because for some purposes it's convenient or straight-up necessary to be able to ask, for a given text node, what element is its parent β€” and obviously you can't do that if the node is just a text string. πŸ’…

Heads up: these ~text objects are not recognized as text nodes by methods like as_text. The assumption is that you'll call $h->objectify_text, do whatever task you needed that for, and then call $h->deobjectify_text before you call anything like $h->as_text. πŸ™ˆ

✨ deobjectify_text ✨

$h->deobjectify_text();

This undoes the whole $h->objectify_text situation. Like, it takes any ~text pseudo-elements in the tree at/under $h and deletes each one, replacing each with the content of its text attribute. 🧚

Careful, bestie: if $h itself is a ~text pseudo-element, it will be destroyed β€” a condition you may need to treat specially in your calling code (since it means you can't very well do anything with $h after that 😭). So that you can detect that condition: if $h is itself a ~text pseudo-element, this method returns the value of the text attribute, which should be a defined value; in all other cases, it returns undef.

(This method assumes that no ~text pseudo-element has any children. Periodt.)

✨ number_lists ✨

$h->number_lists();

For every UL, OL, DIR, and MENU element at/under $h, this sets a _bullet attribute for every child LI element. πŸ”₯

For LI children of an OL, the _bullet attribute's value will be something like 4., d., D., IV., or iv., depending on the OL element's type attribute. LI children of a UL, DIR, or MENU get their _bullet attribute set to *.

There should be no other LIs (i.e., except as children of OL, UL, DIR, or MENU elements), and if there are, they are unaffected. πŸ’€

✨ has_insane_linkage ✨

$h->has_insane_linkage

This one's for testing whether this element or the elements under it have linkage attributes (_parent and _content) whose values are deeply aberrant. The vibe check fails if:

  • there are undefs in a content list;
  • an element appears in the content lists of more than one element;
  • the _parent attribute of an element doesn't match its actual parent;
  • or an element appears as its own descendant (i.e., if there is a cyclicity in the tree). πŸŒ€

This returns empty list (or false, in scalar context) if the subtree's linkage methods are sane; otherwise it returns two items (or true, in scalar context): the element where the error occurred, and a string describing the error.

This method is provided mainly for debugging and troubleshooting β€” it should be quite impossible for any document constructed via HTML::TreeBuilder to parse into a non-sane tree (since it's not the content of the tree per se that's in question, but whether the tree in memory was properly constructed); and it should be impossible for you to produce an insane tree just thru reasonable use of normal documented structure-modifying methods. But if you're constructing your own trees and your program is going into infinite loops as during calls to traverse() or any of the secondary structural methods, then as part of debugging, consider calling has_insane_linkage on the tree. πŸ”

✨ element_class ✨

$classname = $h->element_class();

This method returns the class which will be used for new elements. It defaults to HTML::Element, but can be overridden by subclassing or esoteric means best left to those will will read the source and then not complain when those esoteric means change. (Just subclass. 😌)


πŸ‘‘ CLASS METHODS πŸ‘‘

✨ Use_Weak_Refs ✨

$enabled = HTML::Element->Use_Weak_Refs;
HTML::Element->Use_Weak_Refs( $enabled );

This method lets you check whether weak reference support is enabled, and to enable or disable it. For the deets, see Weak References. $enabled is true if weak references are enabled. ⭐

Do not switch this in the middle of your program, and you probably shouldn't use it at all. Existing trees are not affected by this method (until you start modifying nodes in them).

Throws an exception if you attempt to enable weak references and your Perl or Scalar::Util does not support them.

Disabling weak reference support is deprecated. 🚩


🌈 SUBROUTINES 🌈

✨ Version ✨

This subroutine is deprecated. Please use the standard VERSION method (e.g. HTML::Element->VERSION) instead.

✨ ABORT OK PRUNE PRUNE_SOFTLY PRUNE_UP ✨

Constants for signalling back to the traverser. πŸŽ€


πŸ’€ BUGS πŸ’€

  • If you want to free the memory associated with a tree built of HTML::Element nodes, and you have disabled weak references, then you will have to delete it explicitly using the delete method. See Weak References.
  • There's almost nothing to stop you from making a "tree" with cyclicities (loops) in it, which could, for example, make the traverse method go into an infinite loop. So don't make cyclicities! (If all you're doing is parsing HTML files and looking at the resulting trees, this will never be a problem for you.) πŸŒ€
  • There's no way to represent comments or processing directives in a tree with HTML::Elements. Not yet, at least.
  • There's (currently) nothing to stop you from using an undefined value as a text segment. If you're running under perl -w, however, this may make HTML::Element's code produce a slew of warnings. 😭

🌸 NOTES ON SUBCLASSING 🌸

You are welcome to derive subclasses from HTML::Element, but you should be aware that the code in HTML::Element makes certain assumptions about elements (and "element" here means ONLY an object of class HTML::Element, or of a subclass of HTML::Element): 🫢

  • The value of an element's _parent attribute must either be undef or otherwise false, or must be an element.
  • The value of an element's _content attribute must either be undef or otherwise false, or a reference to an (unblessed) array. The array may be empty; but if it has items, they must ALL be either mere strings (text segments), or elements.
  • The value of an element's _tag attribute should, at least, be a string of printable characters.

Moreover, bear these rules in mind, bestie:

  • Do not break encapsulation on objects. That is, access their contents only thru $obj->attr or more specific methods. πŸ”’
  • You should think twice before completely overriding any of the methods that HTML::Element provides. (Overriding with a method that calls the superclass method is not so bad, though.)

⭐ SEE ALSO ⭐

HTML::Tree; HTML::TreeBuilder; HTML::AsSubs; HTML::Tagset; and, for the morbidly curious, HTML::Element::traverse. πŸ‘€


πŸŽ€ ACKNOWLEDGEMENTS πŸŽ€

Thanks to Mark-Jason Dominus for a POD suggestion. πŸ’–


πŸ’œ AUTHOR πŸ’œ

Current maintainers:

  • Christopher J. Madsen <perl AT cjmweb.net>
  • Jeff Fearn <jfearn AT cpan.org>

Original HTML-Tree author:

  • Gisle Aas

Former maintainers:

  • Sean M. Burke
  • Andy Lester
  • Pete Krawczyk <petek AT cpan.org>

You can follow or contribute to HTML-Tree's development at <https://github.com/kentfredric/HTML-Tree>.


Copyright 1995-1998 Gisle Aas, 1999-2004 Sean M. Burke, 2005 Andy Lester, 2006 Pete Krawczyk, 2010 Jeff Fearn, 2012 Christopher J. Madsen.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The programs in this library are distributed in the hope that they will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.


okay that's the whole page, we're done, slay πŸ’…βœ¨ this was the perl v5.42.0 build, dated 2017-09-01, filed under HTML::Element(3pm) β€” ily, go build some trees πŸŒˆπŸ“

πŸ“¦ where this page comes from