perldoc > HTML::Element

πŸ“› NAME

HTML::Element - Class for objects that represent HTML elements

πŸš€ Quick Reference

Use CaseCommandDescription
πŸ”§ Create elementHTML::Element->new('tag', attr=>val)Create new HTML element object
βš™οΈ Get/set attribute$h->attr('attr', $newval)Read or set element attribute value
🏷️ Get tag name$h->tag()Return element's tag name (lowercase)
βž• Add child$h->push_content($child)Append content to element
πŸ“‹ Get children$h->content_list()Return list of child nodes
πŸ” Find elements$h->look_down(...)Find matching descendant elements
🌐 Render HTML$h->as_HTML()Serialize element tree as HTML string
πŸ“ Extract text$h->as_text()Get plain text content (no tags)
πŸ“‹ Clone tree$h->clone()Deep copy element and all descendants
πŸ—‘οΈ Delete tree$h->delete()Detach and destroy element with children
πŸ”— Find parent$h->parent()Return parent element (undef if root)
πŸ“Š Dump tree$h->dump()Print indented tree structure for debugging

πŸ“Œ VERSION

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

πŸ“‹ 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

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. 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

πŸ”§ new

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

This constructor method returns a new HTML::Element object. The tag name is a required argument; it will be forced to lowercase. Optionally, you can specify other initial attributes at object creation time.

🏷️ attr

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

Returns (optionally sets) the value of the given attribute of $h. The attribute name (but not the value, if provided) is forced to lowercase. If trying to read the value of an attribute not present for this element, the return value is undef. If setting a new value, the old value of that attribute is returned.

If methods are provided for accessing an attribute (like "$h->tag" for "_tag", "$h->content_list", etc. below), use those instead of calling attr "$h->attr", whether for reading or setting.

Note that setting an attribute to "undef" (as opposed to "", the empty string) actually deletes the attribute.

🏷️ tag

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

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

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

πŸ”— parent

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

Returns (optionally sets) the parent (aka "container") for this element. The parent should either be undef, or should be another element. You should not use this to directly set the parent of an element. Instead use any of the other methods under "Structure-Modifying Methods". Note that "not($h->parent)" is a 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 β€” i.e., what nodes (elements or text segments) are inside/under this element. (Note that this may be an empty list.) In a scalar context, returns the count of the items.

πŸ“¦ content

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

This somewhat deprecated method returns the content of this element; but unlike content_list, this returns either undef (which you should understand to mean no content), or a reference to the array of content items. While older code should feel free to continue to use "$h->content", new code should use "$h->content_list" in almost all conceivable cases.

πŸ“¦ content_array_ref

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

This is like "content" (with all its caveats and deprecations) except that it is guaranteed to return an array reference.

πŸ“‹ content_refs_list

@content_refs = $h->content_refs_list;

This returns a list of scalar references to each element of $h's content list. This is useful in case you want to in-place edit any large text segments without having to get a copy of the current value of that segment value, modify that copy, then use the "splice_content" to replace the old with the new.

🚩 implicit

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

Returns (optionally sets) the "_implicit" attribute. This attribute is a flag that's used for indicating that the element was not originally present in the source, but was added to the parse tree (by HTML::TreeBuilder, for example) in order 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", where "$h->insert_element(NEW)" will actually insert a new element. If you set "$h->pos($element)", be sure that $element is either $h, or an element under $h.

πŸ“‹ all_attr

%attr = $h->all_attr();

Returns all this element's attributes and values, as key-value pairs. This will include any "internal" attributes (i.e., ones not present in the original element, and which will not 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 ("_").

πŸ“‹ 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.

πŸ“‹ all_external_attr

%attr = $h->all_external_attr();

Like "all_attr", except that internal attributes are not present.

πŸ“‹ all_external_attr_names

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

Like "all_attr_names", except that internal attributes' names are not present (or counted).

πŸ†” id

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

Returns (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 value.

πŸ†” 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's set to a likely-to-be-unique value, and returned. (The "f" is for "force".)

πŸ—οΈ STRUCTURE-MODIFYING METHODS

These methods are provided for modifying the content of trees by adding or changing nodes as parents or children of other nodes.

βž• push_content

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

Adds the specified items to the end of the content list of the element $h. The items of content to be added should each be either a text segment (a string), an HTML::Element object, or an arrayref. Arrayrefs are fed thru "$h->new_from_lol(that_arrayref)" to convert them into elements, before being added to the content list of $h. This means you can say things concise things like:

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

See the "new_from_lol" method's documentation, far below, for more explanation. Returns $h (the element itself). The push_content method will try to consolidate adjacent text segments while adding to the content list.

βž• unshift_content

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

Just like "push_content", but adds to the beginning of the $h element's content list. The items of content to be added should each be either a text segment (a string), an HTML::Element object, or an arrayref (which is fed thru "new_from_lol"). The unshift_content method will try to consolidate adjacent text segments while adding to the content list. Returns $h (the element itself).

βœ‚οΈ splice_content

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

Detaches the elements from $h's list of content-nodes, starting at $offset and continuing for $length items, replacing them with the elements of the following list, if any. Returns the elements (if any) removed from the content-list. If $offset is negative, then it starts that far from the end of the array, just like Perl's normal "splice" function. If $length and the following list is omitted, removes everything from $offset onward.

πŸ”— detach

$old_parent = $h->detach();

This unlinks $h from its parent, by setting its 'parent' attribute to undef, and by removing it from the content list of its parent (if it had one). The return value is the parent that was detached from (or undef, if $h had no parent to start with). Note that neither $h nor its parent are explicitly destroyed.

πŸ”— detach_content

@old_content = $h->detach_content();

This unlinks all of $h's children from $h, and returns them. Note that these are not explicitly destroyed; for that, you can just use "$h->delete_content".

πŸ”„ replace_with

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

This replaces $h in its parent's content list with the nodes specified. The element $h (which by then may have no parent) is returned. This causes a fatal error if $h has no parent. The list of nodes to insert may contain $h, but at most once. Note that this method does not destroy $h if weak references are turned off β€” use "$h->replace_with(...)->delete" if you need that.

⬅️ preinsert

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

Inserts the given nodes right BEFORE $h in $h's parent's content list. This causes a fatal error if $h has no parent. 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. This causes a fatal error if $h has no parent. None of the given nodes should be $h or other children of $h. Returns $h.

πŸ”„ replace_with_content

$h->replace_with_content();

This replaces $h in its parent's content list with its own content. The element $h (which by then has no parent or content of its own) is returned. This causes a fatal error if $h has no parent. Note that this does not destroy $h if weak references are turned off β€” use "$h->replace_with_content->delete" if you need that.

πŸ—‘οΈ delete_content

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

Clears the content of $h, calling "$h->delete" for each content element. Compare with "$h->detach_content". Returns $h. "destroy_content" is an alias for this method.

πŸ—‘οΈ delete

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

Detaches this element from its parent (if it has one) and explicitly destroys the element and all its descendants. The return value is the empty list (or "undef" in scalar context). Before version 5.00 of HTML::Element, you had to call "delete" when you were finished with the tree, or your program would leak memory. This is no longer necessary if weak references are enabled, see "Weak References".

πŸ“‹ destroy

An alias for "delete".

πŸ“‹ destroy_content

An alias for "delete_content".

πŸ“‹ clone

$copy = $h->clone();

Returns a copy of the element (whose children are clones (recursively) of the original's children, if any). The returned element is parentless. Any '_pos' attributes present in the source element/tree will be absent in the copy. You are 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.

πŸ“‹ clone_list

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

Returns a list consisting of a copy of each node given. Text segments are simply copied; elements are cloned by calling "$it->clone" on each of them. Note that this must be called as a class method, not as an instance method.

πŸ“‹ normalize_content

$h->normalize_content

Normalizes the content of $h β€” i.e., concatenates any adjacent text nodes. (Any undefined text segments are turned into empty-strings.) Note that this does not recurse into $h's descendants.

πŸ—‘οΈ delete_ignorable_whitespace

$h->delete_ignorable_whitespace()

This traverses under $h and deletes any text segments that are ignorable whitespace. You should not use this if $h is under a "<pre>" element.

πŸ“ insert_element

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

Inserts (via push_content) a new element under the element at "$h->pos()". Then 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()" is returned. This method is useful only if your particular tree task involves setting "$h->pos()".

πŸ“€ 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 specified filehandle), in a format useful only for debugging. The structure of the document is shown by indentation (no end tags).

🌐 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 representing in HTML the element and its descendants. The optional argument $entities specifies a string of the entities to encode. For compatibility with previous versions, specify '<>&' here. If omitted or undef, all unsafe characters are encoded as HTML entities. See HTML::Entities for details. If passed an empty string, no entities are encoded.

If $indent_char is specified and defined, the HTML to be output is intented, using the string you specify (which you probably should set to "\t", or some number of spaces, if you specify it).

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. 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 useful value to pass is an empty hashref, "{}", which means that no end-tags are optional for this dump.

πŸ“ as_text

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

Returns a string consisting of only the text parts of the element's descendants. Any whitespace inside the element is included unchanged, but whitespace not in the tree is never added. Text under "<script>" or "<style>" elements is never included in what's returned. If "skip_dels" is true, then text content under "<del>" nodes is not included in what's returned.

πŸ“ 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 just like "as_text(...)" except that leading and trailing whitespace is deleted, and any internal whitespace is collapsed. This will not remove non-breaking spaces, Unicode spaces, or any other non-ASCII whitespace unless you supply the extra characters as a string argument.

❄️ as_XML

$s = $h->as_XML()

Returns a string representing in XML the element and its descendants. The XML is not indented.

πŸ“‹ as_Lisp_form

$s = $h->as_Lisp_form();

Returns a string representing the element and its descendants as a Lisp form. Unsafe characters are encoded as octal escapes. The Lisp form is indented, and contains external ("href", etc.) as well as internal attributes ("_tag", "_content", "_implicit", etc.), except for "_parent", which is omitted.

πŸ“‹ format

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

Formats text output. Defaults to HTML::FormatText. Takes a second argument that is a reference to a formatter.

🏷️ starttag

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

Returns a string representing the complete start tag for the element. I.e., leading "<", tag name, attributes, and trailing ">". All values are surrounded with double-quotes, and appropriate characters are encoded. If $entities is omitted or undef, all unsafe characters are encoded as HTML entities.

🏷️ 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., "</", tag name, and ">".

🏷️ endtag_XML

$end = $h->endtag_XML();

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

πŸ” 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.

πŸ” is_inside

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

Returns true if the $h element is, or is contained anywhere inside an element that is any of the ones listed, or whose tag name is any of the tag names listed. You can use any mix of elements and tag names.

πŸ“­ 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 that 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.

πŸ”’ pindex

$index = $h->pindex();

Return the index of the element in its parent's contents array. 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), then this returns undef. In list context: returns all the nodes that're the left siblings of $h (starting with the leftmost).

➑️ right

$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.

πŸ“ 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 is a member of. The address consists of 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. The second form returns the node at the given address in the tree that $h is a part of.

πŸ“ 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.

πŸ”— 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.

🏷️ 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.

πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ 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.

πŸ” 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 none.

πŸ“‹ find

This is just an alias to "find_by_tag_name".

πŸ” find_by_attribute

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

In a list context, returns a list of elements at or under $h that have the specified attribute, and have the given value for that attribute. In a scalar context, returns the first such element found, or undef if none. This method is deprecated in favor of the more expressive "look_down" method.

πŸ” 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), looking for elements matching the criteria you specify. In list context, returns all elements that match all the given criteria; in scalar context, returns the first such element (or undef, if nothing matched).

There are three kinds of criteria you can specify:

Note that comparison of string attribute-values against the string value in "(attr_name, attr_value)" is case-INsensitive! Note also that "look_down" considers "" (empty-string) and undef to be different things in attribute values.

πŸ” 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).

🚢 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

πŸ”— 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".) In scalar context, returns the first such value, or undef if none.

πŸ—ΊοΈ 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 to all elements that have that tag name.

πŸ”— extract_links

$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 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.

πŸ“‹ 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.

πŸ” 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.). Sameness of descendant elements is tested, recursively, with "$child1->same_as($child_2)", and sameness of text segments is tested with "$segment1 eq $segment2".

πŸ”§ 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.))).

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

An example:

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;

πŸ“¦ 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 in an attribute called "text". This method is provided because, for some purposes, it is convenient or necessary to be able, for a given text node, to ask what element is its parent.

πŸ“¦ deobjectify_text

$h->deobjectify_text();

This undoes the effect of "$h->objectify_text". That is, 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.

πŸ”’ 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 "*".

πŸ” has_insane_linkage

$h->has_insane_linkage

This method is for testing whether this element or the elements under it have linkage attributes (_parent and _content) whose values are deeply aberrant: if there are undefs in a content list; if an element appears in the content lists of more than one element; if the _parent attribute of an element doesn't match its actual parent; or if 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.

πŸ›οΈ 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.

πŸ›οΈ CLASS METHODS

πŸͺ’ Use_Weak_Refs

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

This method allows you to check whether weak reference support is enabled, and to enable or disable it. For details, see "Weak References". $enabled is true if weak references are enabled. You should not switch this in the middle of your program, and you probably shouldn't use it at all. 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

πŸ“ 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:

Moreover, bear these rules in mind:

πŸ‘€ 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:

Original HTML-Tree author:

Former maintainers:

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

©️ COPYRIGHT AND LICENSE

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.

HTML::Element
πŸ“› NAME πŸš€ Quick Reference πŸ“Œ VERSION πŸ“‹ SYNOPSIS πŸ“– DESCRIPTION 🌳 HOW WE REPRESENT TREES
πŸͺ’ Weak References
βš™οΈ BASIC METHODS
πŸ”§ new 🏷️ attr 🏷️ tag πŸ”— parent πŸ“‹ content_list πŸ“¦ content πŸ“¦ content_array_ref πŸ“‹ content_refs_list 🚩 implicit πŸ“ pos πŸ“‹ all_attr πŸ“‹ all_attr_names πŸ“‹ all_external_attr πŸ“‹ all_external_attr_names πŸ†” id πŸ†” idf
πŸ—οΈ STRUCTURE-MODIFYING METHODS
βž• push_content βž• unshift_content βœ‚οΈ splice_content πŸ”— detach πŸ”— detach_content πŸ”„ replace_with ⬅️ preinsert ➑️ postinsert πŸ”„ replace_with_content πŸ—‘οΈ delete_content πŸ—‘οΈ delete πŸ“‹ destroy πŸ“‹ destroy_content πŸ“‹ clone πŸ“‹ clone_list πŸ“‹ normalize_content πŸ—‘οΈ delete_ignorable_whitespace πŸ“ insert_element
πŸ“€ DUMPING METHODS
πŸ“Š dump 🌐 as_HTML πŸ“ as_text πŸ“ as_trimmed_text ❄️ as_XML πŸ“‹ as_Lisp_form πŸ“‹ format 🏷️ starttag 🏷️ starttag_XML 🏷️ endtag 🏷️ endtag_XML
πŸ” SECONDARY STRUCTURAL METHODS
πŸ” is_inside πŸ“­ is_empty πŸ”’ pindex ⬅️ left ➑️ right πŸ“ address πŸ“ depth 🌳 root πŸ”— lineage 🏷️ lineage_tag_names πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ descendants πŸ“‹ descendents πŸ” find_by_tag_name πŸ“‹ find πŸ” find_by_attribute πŸ” look_down πŸ” look_up 🚢 traverse πŸ”— attr_get_i πŸ—ΊοΈ tagname_map πŸ”— extract_links πŸ“‹ simplify_pres πŸ” same_as πŸ”§ new_from_lol πŸ“¦ objectify_text πŸ“¦ deobjectify_text πŸ”’ number_lists πŸ” has_insane_linkage πŸ›οΈ element_class
πŸ›οΈ CLASS METHODS
πŸͺ’ Use_Weak_Refs
πŸ”§ SUBROUTINES
πŸ“Œ Version 🚦 ABORT OK PRUNE PRUNE_SOFTLY PRUNE_UP
πŸ› BUGS πŸ“ NOTES ON SUBCLASSING πŸ‘€ SEE ALSO πŸ™ ACKNOWLEDGEMENTS ✍️ AUTHOR ©️ COPYRIGHT AND LICENSE

Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 05:23 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^