HTML::O...Element(3)

πŸ“¦ version 0.6.0, in alpine 3.24

πŸ’– HTML::O...Element(3) πŸ’–

User Contributed Perl Documentation bestie, we are so back ✨


🌸 NAME 🌸

HTML::Object::DOM::Element β€” HTML Object, no cap πŸ’…

✨ SYNOPSIS ✨

use HTML::Object::DOM::Element;
my $this = HTML::Object::DOM::Element->new ||
    die( HTML::Object::DOM::Element->error, "\n" );

πŸŽ€ VERSION πŸŽ€

v0.4.0

πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so this module represents an HTML element, and it also contains all the methods for DOM nodes at https://developer.mozilla.org/en-US/docs/Web/API/Node πŸ‘‘ It is inherited by all other element objects in a document, periodt.

This module inherits from HTML::Object::Node and is extended by HTML::Object::XQuery β€” iconic inheritance chain, ngl 🌈

πŸ’€ INHERITANCE πŸ’€

+-----------------------+     +---------------------------+     +-------------------------+     +----------------------------+
| HTML::Object::Element | --> | HTML::Object::EventTarget | --> | HTML::Object::DOM::Node | --> | HTML::Object::DOM::Element |
+-----------------------+     +---------------------------+     +-------------------------+     +----------------------------+

πŸ’… PROPERTIES πŸ’…

All the following properties can be used as lvalue method as well as regular method. For example with baseURI 🫢


🌟 accessKey 🌟

A string representing the access key assigned to the element.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/accessKey for more information.

πŸŽ€ accessKeyLabel πŸŽ€

my $label = $element->accessKeyLabel;

my $btn = $document->getElementById("btn1");
my $shortcutLabel = $btn->accessKeyLabel || $btn->accessKey;
$btn->title .= " [" . uc( $shortcutLabel ) . "]";

Read-only 🫢

Returns a string containing the element's assigned access key.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/accessKeyLabel for more information.

🌸 attributeStyleMap 🌸

Sets or gets the style attribute.

Normally, this is read-only, and represents a StylePropertyMap representing the declarations of the element's style attribute.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attributeStyleMap for more information.

πŸ¦‹ baseURI πŸ¦‹

# Get the base uri, if any
my $uri = $e->baseURI;
$e->baseURI = 'https://example.org/some/where';
# or
$e->baseURI( 'https://example.org/some/where' );

Read-only β€” yes, right above an assignment example, make it make sense 😭 β€” and this returns an URI object representing the base URL of the document containing the Node, if any.

πŸ’– childElementCount πŸ’–

Read-only

Returns the number of child elements of this element.

✨ childNodes ✨

Read-only

This returns an array object containing all the children of this node (including elements, text and comments). This list being live means that if the children of the Node change, the list object is automatically updated. Live list energy, fr fr πŸ”₯

🌈 classList 🌈

The classList property is a read-only property that returns a live HTML::Object::TokenList collection of the class attributes of the element. This can then be used to manipulate the class list.

Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via className πŸ’…

It returns a HTML::Object::TokenList object representing the contents of the element's class attribute. If the class attribute is not set or empty, it returns an empty HTML::Object::TokenList, i.e. a HTML::Object::TokenList with the length property equal to 0.

Although the classList property itself is read-only, you can modify its associated HTML::Object::TokenList using the add(), remove(), replace(), and toggle() methods.

For example:

my $div = $doc->createElement('div');
# use the classList API to remove and add classes
$div->classList->remove("foo");
$div->classList->add("anotherclass");
say $div->outerHTML; # <div class="anotherclass"></div>
# if visible is set remove it, otherwise add it
$div->classList->toggle("visible");
$div->classList->contains("foo");
# add or remove multiple classes
$div->classList->add("foo", "bar", "baz");
$div->classList->remove("foo", "bar", "baz");
# replace class "foo" with class "bar"
$div->classList->replace("foo", "bar");

See also Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/Element/classList πŸ’œ

⭐ className ⭐

Set or get the element class.

Returns a string representing the class of the element.

This method is an lvalue method, so you can assign value like this:

$e->className = "my-class";

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/className πŸŽ€

πŸ“ clientHeight πŸ“

Read-only.

This always returns undef since this has no meaning under perl.

Normally, under JavaScript, this would return a number representing the inner height of the element.

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight πŸ™ˆ

🧚 clientLeft 🧚

This always returns undef since this has no meaning under perl.

Normally, under JavaScript, this would return a number representing the width of the left border of the element.

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/clientLeft 🌸

πŸ’œ clientTop πŸ’œ

This always returns undef since this has no meaning under perl.

Normally, under JavaScript, this would return a number representing the width of the top border of the element.

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop πŸ¦‹

πŸ”₯ clientWidth πŸ”₯

This always returns undef since this has no meaning under perl.

Normally, under JavaScript, this would return a number representing the inner width of the element.

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth ✨

πŸ‘‘ contentEditable πŸ‘‘

Set or get the boolean value where true means the element is editable and a value of false means it is not. Defautls to true β€” yes, that's the source's typo, we're keeping it πŸ’€

$e->contentEditable = 0; # turn off content editability

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/contentEditable for more information.

πŸŽ€ dataset πŸŽ€

<div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth>
  Carina Anand
</div>

var $el = $document->getElementById('user');

# $el->id eq 'user';
# $el->dataset->id eq '1234567890';
# $el->dataset->user eq 'carinaanand';
# $el->dataset->dateOfBirth eq '';

# set a data attribute
$el->dataset->dateOfBirth = "1960-10-03";
# <div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth="1960-10-03">Carina Anand</div>

Read-only

Returns an HTML::Object::ElementDataMap object with which script can read and write the element's custom data attributes (data-*).

The attribute name begins with data-. It can contain only letters, numbers, dashes (-), periods (.), colons (:), and underscores (_). Any ASCII capital letters (A to Z) are converted to lowercase.

Name conversion 🌈

dash-style to camelCase conversion πŸ’…

A custom data attribute name is transformed to a key for the DOMStringMap entry by the following:

  1. Lowercase all ASCII capital letters (A to Z);
  2. Remove the prefix data- (including the dash);
  3. For any dash (U+002D) followed by an ASCII lowercase letter a to z, remove the dash and uppercase the letter;
  4. Other characters (including other dashes) are left unchanged.

camelCase to dash-style conversion πŸ¦‹

The opposite transformation, which maps a key to an attribute name, uses the following:

  1. Restriction: Before transformation, a dash must not be immediately followed by an ASCII lowercase letter a to z;
  2. Add the data- prefix;
  3. Add a dash before any ASCII uppercase letter A to Z, then lowercase the letter;
  4. Other characters are left unchanged.

For example, a data-abc-def attribute corresponds to "<$dataset-"abcDef>>.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset for more information.

🌸 dir 🌸

my $parg = $document->getElementById("para1");
$parg->dir = "rtl";
# change the text direction on a paragraph identified as "para1"

A string, reflecting the dir global attribute, representing the directionality of the element. Possible values are:

  • "ltr" β€” for left-to-right;
  • "rtl" β€” for right-to-left;
  • "auto" β€” for specifying that the direction of the element must be determined based on the contents of the element.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dir for more information.

✨ draggable ✨

A boolean value indicating if the element can be dragged.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/draggable for more information.

πŸ¦‹ enterKeyHint πŸ¦‹

A string defining what action label (or icon) to present for the enter key on virtual keyboards.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/enterKeyHint for more information.

πŸ’– firstChild πŸ’–

Read-only

This returns an element representing the first direct child element of the element, or undef if the element has no child.

⭐ firstElementChild ⭐

Read-only.

It returns the first child element of this element.

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/firstElementChild 🫢

πŸ“ hidden πŸ“

A string or boolean value reflecting the value of the element's hidden attribute.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden for more information.

🧚 id 🧚

Set or get a string representing the id of the element.

# Set it as a regular method
$e->id( 'hello' );
# Set it as a lvalue method
$e->id = 'hello';
# Retrieve it
my $id = $e->id;

See for more information at https://developer.mozilla.org/en-US/docs/Web/API/Element/id πŸ’œ

πŸ’… innerHTML πŸ’…

Set or get the element's content. This returns a string representing the markup of the element's content.

Se for more information (yep, β€œSe”, we're keeping the source typo πŸ’€) at https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML.

πŸ”₯ inert πŸ”₯

A boolean value indicating whether the user agent must act as though the given node is absent for the purposes of user interaction events, in-page text searches ("find in page"), and text selection.

See Mozilla documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert for more information.

innerText ✨

Represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard. This returns a string object. As a setter, it replaces the content inside the selected element, with either a text object or by a string converting any line breaks into <br /"> elements.

When setting some values, this method will ensure that HTML characters are escaped, namely: <, > and new lines are preceded by the <br /> tag.

When the value is retrieved, this is reversed.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

See also textContent in HTML::Object::DOM::Node, as_text in HTML::Object::Element and text in HTML::Object::XQuery.

inputMode πŸŽ€

A string value reflecting the value of the element's inputmode attribute.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inputMode

isConnected πŸ”₯

Returns a boolean indicating whether or not the element is connected (directly or indirectly) to the context object, i.e. the Document object in the case of the normal DOM.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected

isContentEditable πŸ’…

<p id="firstParagraph">Uneditable Paragraph</p>
<p id="secondParagraph" contenteditable="true">Editable Paragraph</p>

my $firstParagraph = $document->getElementById("firstParagraph");
my $secondParagraph = $document->getElementById("secondParagraph");

Read-only

Returns a boolean value indicating whether or not the content of the element can be edited. Use contentEditable to change the value.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/isContentEditable

lang 🌸

A string representing the language of an element's attributes, text, and element contents.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/lang

lastChild πŸ¦‹

Read-only

This returns an element representing the last direct child element of the element, or undef if the element has no child.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild

lastElementChild 🌈

Read-only

Returns the last child element of this element, if any at all.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/lastElementChild

localName ⭐

Read-only

A string representing the local part of the qualified name of the element. This is basically the tag name. This has a special meaning only when using xml, which we do not. So this is just an alias to getName.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/localName

namespaceURI πŸ’œ

Read-only

The namespace URI of the element, or undef if it is no namespace.

This always return undef, because as HTML, we do not deal with namespace, which is used primarily under xml.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/namespaceURI

nextElementSibling 🧚

Read-only

Is an Element, the element immediately following the given one in the tree, or undef if there's no sibling node.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/nextElementSibling

nextSibling πŸ“

Read-only

This returns an element representing the next element in the tree, or undef if there is not such element.

The next node could also be a whitespace or a text. If you want to get the next element and not just any node, use nextElementSibling instead.

nodeName πŸ‘‘

Read-only

This returns a string containing the name of the element. The structure of the name will differ with the element type. E.g. An HTML Element will contain the name of the corresponding tag, like 'audio' for an HTML audio element, a Text element will have the '#text' string, or a Document element will have the '#document' string.

nodeType πŸ’€

Read-only

This returns an integer representing the type of the element. Possible values are:

  1. element node
  2. attribute node
  3. text node
  4. CDATA section node
  5. unused
  6. unsued
  7. processing instruction node
  8. comment node
  9. document node
  10. document type node
  11. document fragment node

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType

nodeValue πŸ™ˆ

This returns or sets the value of the current node.

For document, element or collection, this returns undef and for attribute, text or comment, this sets or returns the objct value.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue

noModule πŸŽ€

A boolean value indicating whether an import script can be executed in user agents that support module scripts.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/noModule

nonce ✨

This returns nothing.

Normally, under JavaScript, this would return the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/nonce

offsetHeight πŸ’–

Sets or gets the property offsetheight.

Normally, under JavaScript, this would be read-only and return a double containing the height of an element, relative to the layout.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight

offsetLeft 🌸

Sets or gets the property offsetleft.

Normally, under JavaScript, this would be read-only and return a double, the distance from this element's left border to its offsetParent's left border.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft

offsetParent πŸ¦‹

Sets or gets the property offsetparent.

Normally, under JavaScript, this would be read-only and return Element that is the element from which all offset calculations are currently computed.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent

offsetTop πŸ”₯

Sets or gets the property offsettop.

Normally, under JavaScript, this would be read-only and return a double, the distance from this element's top border to its offsetParent's top border.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

offsetWidth 🌈

Sets or gets the property offsetwidth.

Normally, under JavaScript, this would be read-only and return a double containing the width of an element, relative to the layout.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

outerHTML ⭐

Returns a string representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

outerText πŸ’œ

Represents the rendered text content of a node and its descendants.

As a getter, it is the same as innerText (it represents the rendered text content of an element and its descendants).

As a setter, it replaces the selected node and its contents with the given value, converting any line breaks into <br /"> elements.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/outerText

ownerDocument 🧚

Read-only

This returns the Document that this element belongs to. If the element is itself a document, returns undef.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument

parentNode πŸ“

Read-only

This returns an element that is the parent of this element. If there is no such element, like if this element is the top of the tree or if does not participate in a tree, this property returns undef.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode

parentElement πŸ‘‘

Read-only

This returns an element that is the parent of this element. If the element has no parent, or if that parent is not an Element, this property returns undef.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

part πŸ’€

This always returns undef, because it has no meaning under perl.

Normally, under JavaScript, this would be a part that represents the part identifier(s) of the element (i.e. set using the part attribute), returned as a DOMTokenList.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

popover πŸ™ˆ

Experimental

Gets and sets an element's popover state via JavaScript (auto or manual), and can be used for feature detection. Reflects the value of the popover global HTML attribute.

If no value are set, this will return the one of the HTML attribute.

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/popover

prefix πŸŽ€

Read-only

This always return undef

Normally, for xml documents, this would be a string representing the namespace prefix of the element, or undef if no prefix is specified.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/prefix

previousElementSibling ✨

Read-only

Returns an Element, the element immediately preceding the given one in the tree, or undef if there is no sibling element.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/previousElementSibling

previousSibling πŸ’–

Read-only

This returns a element representing the previous element in the tree, or undef if there is not such element.

The previous node could also be a whitespace or a text. If you want to get the previous element and not just any node, use previousElementSibling instead.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling

properties 🌸

This does nothing, but return an empty array object

Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/properties

scrollHeight πŸ¦‹

Read-only

This always return undef as this is not applicable under perl.

Normally, under JavaScript, scrollHeight would return a number representing the scroll view height of an element. Under Perl it’s giving β€œnot applicable,” bestie.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

scrollLeft

This always returns undef because it’s simply not applicable under Perl. Normally, under JavaScript, it would set or return a number representing the left scroll offset of the element.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft

scrollTop

This always returns undef β€” again, not applicable under Perl. Normally, under JavaScript, it would set or return a number representing the number of pixels the top of the document is scrolled vertically.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

scrollWidth

Read-only. This always returns undef because it’s not applicable under Perl. Normally, under JavaScript, it would return a number representing the scroll view width of the element.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth

setHTML

Parses and sanitizes a string of HTML and inserts it into the DOM as a subtree of the element. Very β€œclean up your room before guests arrive” energy πŸ’…

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML

shadowRoot

Read-only. Always returns undef.

Normally, under JavaScript, it would return the open shadow root hosted by the element, or null if no open shadow root is present.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot

spellcheck

A boolean value that controls spell-checking. It’s present on all HTML elements, though it doesn’t have an effect on all of them. Iconic β€œI’m here but not always useful” behavior ✨

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/spellcheck for more information.

style

This does nothing except return a new empty hash object.

Normally, it would set or get a CSSStyleDeclaration representing the declarations of the element’s style attribute.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style for more information.

tabIndex

The tabIndex property represents the tab order of the current element.

Tab order is as follows:

  1. Elements with a positive tabIndex. Elements that have identical tabIndex values should be navigated in the order they appear. Navigation proceeds from the lowest tabIndex to the highest tabIndex.
  2. Elements that do not support the tabIndex attribute or support it and assign tabIndex to 0, in the order they appear.

Elements that are disabled do not participate in the tabbing order.

Values do not need to be sequential, nor must they begin with any particular value. They may even be negative, though each browser trims very large values.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/tabIndex

tagName

Read-only. This is merely an alias for getName.

This returns a string with the name of the tag for the given element.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

textContent

This returns or sets the textual content of an element and all its descendants. Main character text energy, fr fr 🫢

Example:

<div id="divA">This is <span>some</span> text!</div>

my $text = $doc->getElementById('divA')->textContent;
# The text variable is now: 'This is some text!'

$doc->getElementById('divA')->textContent = 'This text is different!';
# The HTML for divA is now:
# <div id="divA">This text is different!</div>

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

title

A string containing the text that appears in a popup box when the mouse is over the element.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/title for more information.

translate

A boolean value representing the translation.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/translate for more information.


πŸ’… METHODS πŸ’…

addEventListener

Registers an event handler to a specific event type on the element. This is inherited from HTML::Object::EventTarget.

See "addEventListener" in HTML::Object::EventTarget for more information.

after

Inserts a list of elements or HTML strings in the children list of the element’s parent, just after the element. It’s the β€œexcuse me, coming through, I’m right after them” of DOM methods πŸ¦‹

For example:

Inserting an element:

my $container = $doc->createElement("div");
my $p = $doc->createElement("p");
$container->appendChild( $p );
my $span = $doc->createElement("span");

$p->after( $span );

say( $container->outerHTML );
# "<div><p></p><span></span></div>"

Inserting an element and text:

my $container = $doc->createElement("div");
my $p = $doc->createElement("p");
$container->appendChild( $p );
my $span = $doc->createElement("span");

$p->after( $span, "Text" );

say( $container->outerHTML );
# "<div><p></p><span></span>Text</div>"

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/after

append

Inserts a set of element objects or HTML strings after the last child of the element.

It returns the objects thus inserted as an array object.

Differences from appendChild:

  1. append allows you to also append HTML strings, whereas appendChild only accepts element objects.
  2. append returns the current element object, whereas appendChild returns the appended element object.
  3. append can append several elements and strings, whereas appendChild can only append one element.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/append

appendChild

Adds the specified child element argument as the last child to the current element. If the argument references an existing element on the DOM tree, the element will be detached from its current position and attached at the new position.

Returns the appended object.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

attachInternals

This does nothing.

Normally, under JavaScript, it would set or return an ElementInternals object, and enable a custom element to participate in HTML forms.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals for more information.

before

Inserts a set of elements or HTML strings in the children list of the element’s parent, just before the element. Pre-game placement, no cap πŸ’œ

For example:

my $container = $doc->createElement("div");
my $p = $doc->createElement("p");
$container->appendChild( $p );
my $span = $doc->createElement("span");

$p->before(span);

say( $container->outerHTML );
# "<div><span></span><p></p></div>"

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/before

blur

This does nothing.

Normally, under JavaScript, it would remove keyboard focus from the currently focused element.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur for more information.

click

Sends a mouse click event to the element.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click for more information.

cloneNode

Clone an element, and optionally, all of its contents. By default, it clones the content of the element.

Returns the element cloned.

closest

Returns the element which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.

For example:

<article>
<div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
    <div id="div-03">Here is div-03</div>
    </div>
</div>
</article>

my $el = $doc->getElementById('div-03');
my $r1 = $el->closest("#div-02");
# returns the element with the id C<div-02>

my $r2 = $el->closest("div div");
# returns the closest ancestor which is a div in div, here it is the C<div-03> itself

my $r3 = $el->closest("article > div");
# returns the closest ancestor which is a div and has a parent article, here it is the C<div-01>

my $r4 = $el->closest(":not(div)");
# returns the closest ancestor which is not a div, here it is the outmost article

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

compareDocumentPosition

Compares the position of the current element against another element in any other document.

my $head = $doc->head;
my $body = $doc->body;

if( $head->compareDocumentPosition( $body ) & HTML::Object::Element->Node.DOCUMENT_POSITION_FOLLOWING )
{
    say( 'Well-formed document' );
}
else
{
    say( '<head> is not before <body>' );
}

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition

contains

Returns a true or false value indicating whether or not an element is a descendant of the calling element.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/contains

dispatchEvent

Dispatches an event to this element in the DOM and returns a boolean value that indicates whether no handler canceled the event.

This is inherited from HTML::Object::EventTarget.

See "dispatchEvent" in HTML::Object::EventTarget for more information.

focus

This does nothing.

Normally, under JavaScript, it would make the element the current keyboard focus.

See Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus for more information.

getAttribute

Retrieves the value of the named attribute from the current node and returns it as a string.

Example:

my $parser = HTML::Object::DOM->new;
my $doc = $parser->parse_data( q{<div id="div1">Hi Champ!</div>} );

# in a console
my $div1 = $doc->getElementById('div1');
# => <div id="div1">Hi Champ!</div>

my $exampleAttr = $div1->getAttribute('id');
# => "div1"

my $align = $div1->getAttribute('align');
# => null

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

getAttributeNames

Returns an array object of attribute names from the current element.

Example:

<div id="hello" class="opened" data-status="ok"></div>
my $div = $doc->getElementById( 'hello' );
my $arr = $div->getAttributeNames; # id class data-status
$arr->foreach(sub
{
    say $_;
});
# would print:
# id
# class
# data-status

Peep the full deets at https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames πŸ’–


getAttributeNode

Okay so this one grabs the node version of a named attribute off the current node and hands it back to you as an Attr. Not the value, bestie β€” the whole node. πŸ’…

Example time:

# html: <div id="top" />
my $t = $doc->getElementById("top");
my $idAttr = $t->getAttributeNode("id");
say( $idAttr->value eq "top" ); # 1

MDN has the lore: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNode ✨

getAttributeNodeNS

Lowkey this one always returns undef because there's no support for namespace here, periodt.

What it would do: retrieve the node representation of the attribute with the specified name and namespace, from the current node, and return it as an Attr.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNodeNS πŸ¦‹

getAttributeNS

Same deal β€” always returns undef, still no namespace support fr fr. 😭

For the record, its whole personality would be: retrieve the value of the attribute with the specified namespace and name from the current node and return it as a string.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNS 🌸

getElementsByClassName

Give it a space-delimited list of classes, or just a list of classes, and it returns an array object holding every descendant of the current element that has the classes you asked for. Obsessed.

my $array = $element->getElementsByClassName('test');

This example finds all elements with a class of test that are also descendants of the element with the id of main:

my $array = $doc->getElementById('main')->getElementsByClassName('test');

Wanna find elements whose class lists include both red and test? Slay:

$element->getElementsByClassName('red test');

or, equivalently:

$element->getElementsByClassName('red', 'test');

Now go inspect the results πŸ‘‘

my $matches = $element->getElementsByClassName('colorbox');

for( my $i=0; $i<$matches->length; $i++ )
{
    $matches->[$i]->classList->remove('colorbox');
    $matches->get($i)->classList->add('hueframe');
}

or, somewhat more streamlined:

$matches->foreach(sub
{
    $_->classList->remove('colorbox');
    $_->classList->add('hueframe');
});

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName πŸŽ€

getElementsByTagName

Hand it a tag name and it returns an array object stuffed with all the descendant elements of that particular tag name, going down from the current element. 🫢

The special string "*" represents all elements. Iconic.

# Check the status of each data cell in a table
my $cells = $doc->getElementById('forecast-table')->getElementsByTagName('td');

$cells->foreach(sub
{
    my $cell = shift( @_ ); $_ is available too
    my $status = $cell->getAttribute('data-status');
    if( $status === 'open' )
    {
        # Grab the data
    }
});
Heads up bestie: all descendants of the specified element get searched, but not the element itself. πŸ’€

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName ⭐

getElementsByTagNameNS

Yeah so this always returns undef β€” you already know why β€” no support for namespace. πŸ™ˆ

Normally, under JavaScript, this would return a live HTMLCollection containing all descendant elements of a particular tag name and namespace, from the current element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagNameNS 🌈

getElementsByTagNames

Feed it a space-separated string of tag names, or an array reference of tag names, or just a list of tag names, and it returns an array object of descendant elements matching those tag names. Versatile queen. πŸ‘‘

This is a non-standard method, courtesy of John Resig β€” https://johnresig.com/blog/comparing-document-position/#postcomment πŸ¦‹

getNextSibling

Non-standard method, and it's literally just an alias for the property nextSibling. That's it. That's the method. πŸ’…

getPreviousSibling

Same energy β€” non-standard, and an alias for the property previousSibling. ✨

getRootNode

Returns the context object's root, which optionally includes the shadow root if it's available.

https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode 🌸

hasAttribute

Give it an attribute name and it returns a boolean β€” did the element have that attribute or not, no cap.

my $foo = $doc->getElementById("foo");
if( $foo->hasAttribute("bar") )
{
    # do something
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute πŸ’–

hasAttributeNS

Always returns undef β€” say it with me: no support for namespace. 😭

Its intended job would be: return a boolean indicating whether the element has the specified attribute, in the specified namespace, or not.

hasAttributes

Returns a boolean telling you whether the element has one or more HTML attributes present.

my $foo = $doc->getElementById('foo');
if( $foo->hasAttributes() )
{
    # Do something with '$foo->attributes'
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes πŸŽ€

hasChildNodes

Normally, under JavaScript, this would return a boolean saying whether or not the element has any child elements. 🫢

https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes ⭐

hidePopover

Experimental πŸ§ͺ

This does nothing. Truly the main character of doing nothing.

Normally, under JavaScript, this would hide a popover element by removing it from the top layer and styling it with display: none.

Mozilla docs for the vibes: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidePopover πŸ’€

insertAdjacentElement

You give it a position and an element, and it inserts that element node at the given position relative to the element it's invoked on. Sneaky but valid. πŸ‘‘

It returns the element that was inserted, or undef if the insertion failed.

It returns a HTML::Object::SyntaxError error if the position you specified isn't a recognised value.

It returns a HTML::Object::TypeError error if the element you specified isn't a valid element.

The position can be any one of these (case insensitive):

  • "beforebegin" β€” before the targetElement itself.
  • "afterbegin" β€” just inside the targetElement, before its first child.
  • "beforeend" β€” just inside the targetElement, after its last child.
  • "afterend" β€” after the targetElement itself.

Picture it:

<!-- beforebegin -->
<p>
    <!-- afterbegin -->
    foo
    <!-- beforeend -->
</p>
<!-- afterend -->

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement 🌈

insertAdjacentHTML

Give it a position and some text, and it parses that text as HTML then inserts the resulting nodes into the tree at the position you gave. Chef's kiss. πŸ“

It takes the same position parameter as insertAdjacentElement.

It returns the newly created objects from parsing the html data β€” the ones that got inserted β€” as an array object, or undef if the insertion failed.

It returns a HTML::Object::SyntaxError error if the position specified isn't a recognised value.

It returns a HTML::Object::TypeError error if the element specified isn't a valid element.

Example:

# <div id="one">one</div>
my $d1 = $doc->getElementById('one');
$d1->insertAdjacentHTML('afterend', q{<div id="two">two</div>});

# At this point, the new structure is:
# <div id="one">one</div><div id="two">two</div>

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML πŸ¦‹

insertAdjacentText

Give it a position and a text string β€” or a list of text strings that'll get concatenated β€” and it inserts that text at the given position relative to the element it's invoked upon. πŸ’…

It takes the same position parameter as insertAdjacentElement.

It returns the newly created text node that was inserted, or undef if the insertion failed.

It returns a HTML::Object::SyntaxError error if the position specified isn't a recognised value.

It returns a HTML::Object::TypeError error if the element specified isn't a valid element.

Example:

$beforeBtn->addEventListener( click => sub
{
    $para->insertAdjacentText('afterbegin',$textInput->value);
});

$afterBtn->addEventListener( click => sub
{
    $para->insertAdjacentText('beforeend',$textInput->value);
});

Or:

$para->insertAdjacentText( beforesend => 'Some chunks', 'of', 'text to insert' );

Or, more simply:

$para->insertAdjacentText( beforesend => qw( Some chunks of text to insert ) );

But bestie, these ones would fail since there's no data provided:

$para->insertAdjacentText( beforesend => '' );
$para->insertAdjacentText( beforesend => undef );
$para->insertAdjacentText( beforesend => '', '', '' );

So make sure the data you submit is not zero length, mmkay? 😭

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText 🌸

insertBefore

Inserts an element before the reference element, as a child of a specified parent element. Classic glow-up move. ✨

https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore πŸ’–

isDefaultNamespace

Accepts a namespace URI as an argument and returns a boolean β€” true if that namespace is the default namespace on the given element, false if not. Simple as. πŸŽ€

https://developer.mozilla.org/en-US/docs/Web/API/Node/isDefaultNamespace ⭐

isEqualNode

Returns a boolean indicating whether or not two elements are of the same type and all their defining data points match. πŸ‘‘

Two elements are equal when they have the same type, the same defining characteristics (think their ID, number of children, and so forth), matching attributes, and so on. The exact set of data points that has to match varies depending on the types of the elements involved β€” iykyk.

https://developer.mozilla.org/en-US/docs/Web/API/Node/isEqualNode πŸ¦‹

isSameNode πŸ’…

Returns a boolean value telling you whether the two elements are literally the same β€” like, they reference the same object. No clones, no twins, same actual thing.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/isSameNode

lookupNamespaceURI πŸ¦‹

Takes a prefix and returns the namespace URI tied to it on the given element if it finds one β€” and undef if not. If you pass undef as the prefix, it gives you the default namespace.

It always returns an empty string and http://www.w3.org/XML/1998/namespace if the prefix is xml.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupNamespaceURI

lookupPrefix 🌸

This always returns undef.

It's also described as returning a string containing the prefix for a given namespace URI, if present, and undef if not. Both things are in the original, bestie β€” I'm just reporting the lore faithfully.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupPrefix

matches ✨

Give it a CSS selector string, plus an optional hash or hash reference, and it returns a boolean value: would this element be selected by that selector string or not?

Example:

<ul id="birds">
    <li>Orange-winged parrot</li>
    <li class="endangered">Philippine eagle</li>
    <li>Great white pelican</li>
</ul>

my $birds = $doc->getElementsByTagName('li');

for( my $i = 0; $i < $birds->length; $i++ )
{
    if( $birds->[$i]->matches('.endangered') )
    {
        say('The ' + $birds->[i]->textContent + ' is endangered!');
    }
}
# The Philippine eagle is endangered!

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

new_attribute πŸŽ€

Returns a new HTML::Object::DOM::Attribute object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_closing πŸ’œ

Returns a new HTML::Object::DOM::Closing object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_collection_elements 🌈

Returns a new HTML::Object::DOM::Collection object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_comment πŸ“

Returns a new HTML::Object::DOM::Comment object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_document πŸ”₯

Returns a new HTML::Object::DOM::Document object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_element πŸ‘‘

Returns a new HTML::Object::DOM::Element object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_nodelist 🧚

Returns a new HTML::Object::DOM::NodeList object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_parser 🌟

Returns a new HTML::Object::DOM object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_space 🫢

Returns a new HTML::Object::DOM::Space object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

new_text πŸ’–

Returns a new HTML::Object::DOM::Text object, passing it whatever arguments were provided, and returns the newly instantiated object.

If an error occurred, this returns undef and sets an error.

normalize πŸ’«

Clean up all the text elements under this element β€” merge adjacent ones, remove empty ones.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Node/normalize

prepend πŸŽ‰

Provided with a list of node objects (this includes element objects) or text, or a mixture of them, and this inserts them before the first child of the element.

It returns the objects thus inserted as an array object.

It returns a HTML::Object::HierarchyRequestError error if the objects cannot be inserted at the specified point into the hierarchy.

It returns a HTML::Object::TypeError error if any argument provided is neither a text string nor a node object.

It returns a HTML::Object::SyntaxError error if no argument was provided.

Upon success, it returns an array objects of the nods thus prepended, and upon error, it returns undef and sets one of the errors aforementioned.

Example:

Prepending an element:

my $div = $doc->createElement("div");
my $p = $doc->createElement("p");
my $span = $doc->createElement("span");
$div->append($p);
$div->prepend($span);

# Array object containing <span>, <p>
my $list = $div->childNodes;

Prepending text:

my $div = $doc->createElement("div");
$div->append("Some text");
$div->prepend("Headline: ");

# "Headline: Some text"
say( $div->textContent );

Prepending both an element and some text:

my $div = $doc->createElement("div");
my $p = $doc->createElement("p");
$div->prepend("Some text", $p);

# Array object containing "Some text", <p>
my $list = $div->childNodes;

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/prepend

querySelector πŸ”

Provided with a list of CSS selector strings, and this returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.

If nothing is found, it returns a smart undef β€” so you can tell it apart from an error and it still gets treated as false. On error, it returns undef and sets an error.

It returns a HTML::Object::SyntaxError error if any of the selectors provided is not a valid selector.

Example:

<div>
    <h6>Page Title</h6>
    <div id="parent">
        <span>Love is Kind.</span>
        <span>
            <span>Love is Patient.</span>
        </span>
        <span>
            <span>Love is Selfless.</span>
        </span>
    </div>
</div>
my $parentElement = $doc->querySelector('#parent');
# would need to check that $parentElement is not undef here through...
my $allChildren = $parentElement->querySelectorAll(":scope > span");
$allChildren->foreach(sub
{
    my $item = shift( @_ );
    $item->classList->add("red");
});
<div>
    <h6>Page Title</h6>
    <div id="parent">
        <span class="red">Love is Kind.</span>
        <span class="red">
            <span>Love is Patient.</span>
        </span>
        <span class="red">
            <span>Love is Selfless.</span>
        </span>
    </div>
</div>

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector

querySelectorAll 🌸

Provided with a list of CSS selector strings, and this returns an array object representing a list of elements matching the specified group of selectors which are descendants of the element on which the method was called.

It returns a HTML::Object::SyntaxError error if any of the selectors provided is not a valid selector.

Example:

my $matches = $myBox->querySelectorAll("p");
my $matches = $myBox->querySelectorAll("div.note, div.alert");

Get a list of the document's <p> elements whose immediate parent element is a div with the class highlighted and which are located inside a container whose ID is test.

my $container = $doc->querySelector("#test");
my $matches = $container->querySelectorAll("div.highlighted > p");

Here with an attribute selector:

my $container = $doc->querySelector("#userlist");
my $matches = $container->querySelectorAll("li[data-active='1']");

To access the matched element, see "foreach" in Module::Generic::Array for example:

$matches->foreach(sub
{
    my $elem = shift( @_ ); # $_ is available too
    # Do something with $elem

    # To satisfy array object's foreach and avoid ending abruptly the loop
    return(1);
});

or:

foreach my $elem ( @$matches )
{
    # Do something with $elem
}

A word of caution on some edge case. While the JavaScript equivalent of querySelectorAll takes a document global view at the CSS selector provided, here in perl, it only matches descendants.

For example, the following would return 1 in JavaScript while it would return 0 in our implementation.

<div class="outer">
    <div class="select">
        <div class="inner"></div>
    </div>
</div>

With JavaScript:

var select = document.querySelector('.select');
var inner = select.querySelectorAll('.outer .inner');
inner.length; // 1, not 0 !

With Perl:

my $select = $doc->querySelector('.select');
my $inner = $select->querySelectorAll('.outer .inner');
$inner->length; // 0, not 1 !!

Why is that? Because when JavaScript does it search for the element whose class is inner and who is inside another element whose class is outer, it does not bother JavaScript that outer is a parent of the element on which querySelectorAll is being called, because it retains only the last part of the selector, i.e. inner.

In perl, there is no such elaborate CSS engine that would allow us this level of granularity, and thus it would look for .outer .inner below select and since there are none, it would return 0.

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll

remove πŸ’…

Removes the element from the children list of its parent.

It returns true upon success, and upon error, it returns undef and sets an error.

It returns an HTML::Object::HierarchyRequestError if the element does not have any parent, like so:

my $div = $doc->createElement( 'div' );
$div->remove; # Error returned !

Example:

<div id="div-01">Here is div-01</div>
<div id="div-02">Here is div-02</div>
<div id="div-03">Here is div-03</div>
my $el = $doc->getElementById('div-02');
$el->remove(); # Removes the div with the 'div-02' id

See for more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/remove

removeAttribute

Okay so you hand this one an attribute name, and it removes the attribute with that exact name from the element. Slay.

It returns true when it works, and false otherwise. If you don’t give it an attribute name at all, it returns an HTML::Object::SyntaxError.

Example:

# Given: <div id="div1" align="left" width="200px">
$doc->getElementById("div1")->removeAttribute("align");
# Now: <div id="div1" width="200px">

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute

removeAttributeNode

This one wants an actual attribute node, and it removes the node representation of the named attribute from the current node. It’s basically removeAttribute’s sibling: removeAttribute takes a string attribute name, while removeAttributeNode takes an attribute object.

If something goes wrong, it returns undef and sets an error.

It returns an HTML::Object::SyntaxError if the value you provided is not an attribute object.

Example:

# Given: <div id="top" align="center" />
my $d = $doc->getElementById("top");
my $d_align = $d->getAttributeNode("align");
$d->removeAttributeNode( $d_align ); # <-- passing the attribute object
# align is now removed: <div id="top" />

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttributeNode

removeAttributeNS

This always returns undef, because there is no support for namespace here. Periodt.

Under JavaScript, this would remove the attribute with the specified name and namespace from the current node.

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttributeNS

removeChild

Removes a child element from the current element. The child has to actually be a child of the current element, bestie.

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

removeEventListener

Removes an event listener from the element. This one is inherited from HTML::Object::EventTarget.

See removeEventListener in HTML::Object::EventTarget for more information.

replaceChild

Replaces one child element of the current one with the second one given in the parameter.

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild

replaceChildren

Replaces the existing children of a Node with a specified new set of children. These can be HTML strings or node objects.

It returns an array object of the replaced or removed children. Note that those replaced children will have their parent value set to undef.

You can call it on a node without any argument specified to remove all of its children:

$myNode->replaceChildren();

This method also enables you to easily transfer nodes between elements, since each new node provided will be detached from its previous parent and re-attached under the current element.

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren

replaceWith

Replaces the element in the children list of its parent with a set of Node or DOMString objects.

This method replaces the current element in the children list of its parent with a set of node or strings. Strings that look like HTML are parsed and added as HTML::Object::DOM::Element, and other text strings are inserted as equivalent Text nodes.

This returns a HTML::Object::HierarchyRequestError when a node provided cannot be inserted at the specified point in the hierarchy.

It returns an array object of the newly inserted nodes.

Example:

my $div = $doc->createElement("div");
my $p = $doc->createElement("p");
$div->appendChild( $p );
# Now div is: <div><p></p></div>
my $span = $doc->createElement("span");

$p->replaceWith( $span );

say( $div->outerHTML );
# "<div><span></span></div>"

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith

setAttribute

Provided with a name and a value, this sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

To get the current value of an attribute, use getAttribute; to remove an attribute, use removeAttribute.

Contrary to the original JavaScript equivalent, providing a value with undef results in removing the attribute altogether. Not me dropping a whole attribute with undef, but yes, that’s the vibe.

It returns the current element upon success, and upon error it returns undef and sets an error.

It returns an HTML::Object::InvalidCharacterError object when the attribute name provided contains illegal characters.

It returns an HTML::Object::SyntaxError object when no attribute name was provided.

Example:

Set attributes on a button:

<button>Hello World</button>

my $b = $doc->querySelector("button");

$b->setAttribute("name", "helloButton");
$b->setAttribute("disabled", "");
# <button name="helloButton" disabled="">Hello World</button>

To remove an attribute (same as calling removeAttribute):

$b->setAttribute("disabled", undef);

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

setAttributeNode

Provided with an attribute object, this sets, or possibly replaces, the node representation of the named attribute from the current node.

If a previous attribute existed, it will be replaced and returned.

Example:

<div id="one" align="left">one</div>
<div id="two">two</div>

my $d1 = $doc->getElementById('one');
my $d2 = $doc->getElementById('two');
my $a = $d1->getAttributeNode('align');

$d2->setAttributeNode( $a.cloneNode($true) );

# Returns: 'left'
say( $d2->attributes->get( 'align' )->value );
# or
say( $d2->attributes->{align}->value );

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNode

setAttributeNodeNS

This always returns undef, since namespace is not supported.

Under JavaScript, this would set the node representation of the attribute with the specified name and namespace from the current node.

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS

showPopover

πŸ§ͺ Experimental

This does nothing. Literally nothing.

Normally, under JavaScript, this would show a popover element by adding it to the top layer and removing display: none; from its styles.

See Mozilla documentation for more information: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/showPopover

toggleAttribute

Provided with an attribute name and an optional force value, this toggles a boolean attribute, removing it if it is present and adding it if it is not present, on the specified element.

force is a boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment.

It returns true if attribute name is eventually present, and false otherwise.

It returns an HTML::Object::InvalidCharacterError error if the specified attribute name contains one or more characters which are not valid in attribute names.

Example:

To toggle the disabled attribute of an input field:

<input value="text">
<button>toggleAttribute("disabled")</button>

my $button = $doc->querySelector("button");
my $input = $doc->querySelector("input");

$button->addEventListener( click => sub
{
    $input->toggleAttribute("disabled");
});

More deets on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

togglePopover

πŸ§ͺ Experimental

This does nothing.

Normally, under JavaScript, this would toggle a popover element between the hidden and showing states.

See Mozilla documentation for more information: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/togglePopover

toString

Returns a string representation for this element.

to_number

Returns a HTML::Object::DOM::Number object representing the text value of this element.


✨ EVENTS ✨

Listen to these events using addEventListener in HTML::Object::EventTarget, or by assigning an event listener to the oneventname property of this interface.

Under perl, few events are actually β€œfired” by HTML::Object, and for the others β€” https://developer.mozilla.org/en-US/docs/Web/API/Element#events, also here https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement#events β€” nothing prevents you from triggering whatever events you want, even private non-standard ones, and setting up listeners for them. The audacity, honestly.

Below are the ones actually β€œfired” by HTML::Object.

change

This event is fired when there has been some change to the underlying element. This is also available via the onchange property.

error

This event is fired when an error occurs for this element. This is also available via the onerror property.

Example:

$video->onerror = sub
{
    say( "Error " . $video->error->code . "; details: " . $video->error->message );
}

🌈 EXTENDED 🌈

Inheriting from HTML::Object::EventTarget and extended with HTML::Object::XQuery.

See detailed documentation in HTML::Object::XQuery.


πŸ’– AUTHOR πŸ’–

Jacques Deguest β€” jack@deguest.jp


πŸ‘€ SEE ALSO πŸ‘€

The whole squad:

  • HTML::Object::DOM
  • HTML::Object::DOM::Attribute
  • HTML::Object::DOM::Boolean
  • HTML::Object::DOM::Closing
  • HTML::Object::Collection
  • HTML::Object::DOM::Comment
  • HTML::Object::DOM::Declaration
  • HTML::Object::DOM::Document
  • HTML::Object::DOM::Element
  • HTML::Object::Exception
  • HTML::Object::Literal
  • HTML::Object::DOM::Number
  • HTML::Object::DOM::Root
  • HTML::Object::DOM::Space
  • HTML::Object::DOM::Text
  • HTML::Object::XQuery

Mozilla DOM documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement

Mozilla Element documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element


Copyright(c) 2021 DEGUEST Pte. Ltd.

All rights reserved

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


And that’s a wrap on this page, bestie πŸŽ€ β€” footer source/version is perl v5.42.2, dated 2026-02-15. Slay.

πŸ“¦ where this page comes from