NAME

HTML::Object::DOM::Element - HTML Object

SYNOPSIS

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

VERSION

v0.3.2

DESCRIPTION

This module represents an HTML element and contains also all the methods for DOM nodes. It is inherited by all other element objects in a document.

This module inherits from HTML::Object::Node and is extended by HTML::Object::XQuery

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

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.

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

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

clientHeight

Read-only.

This always return 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

clientLeft

This always return 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

clientTop

This always return 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

clientWidth

This always return 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

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.

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

See Mozilla documentation 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 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 for more information.

draggable

A boolean value indicating if the element can be dragged.

See Mozilla documentation for more information.

enterKeyHint

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

See Mozilla documentation 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

hidden

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

See Mozilla documentation for more information.

id

Set or get an 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

innerHTML

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

Se for more information

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

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See for more information

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.

See Mozilla documentation for more information.

lang

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

See Mozilla documentation for more information.

lastChild

Read-only

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

See for more information

lastElementChild

Read-only

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

See for more information

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"

See for more information

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.

See for more information

nextElementSibling

Read-only

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

See for more information

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

See for more information

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.

See for more information

noModule

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

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See Mozilla documentation for more information.

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.

See for more information

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.

See Mozilla documentation for more information.

ownerDocument

Read-only

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

See for more information

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.

See for more information

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.

See for more information

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.

See for more information

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.

See Mozilla documentation for more information.

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.

See for more information

previousElementSibling

Read-only

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

See for more information

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.

See for more information

properties

This does nothing, but return an empty array object

See Mozilla documentation for more information.

scrollHeight

Read-only

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

Normally, under JavaScript, this would return a number representing the scroll view height of an element.

See for more information

scrollLeft

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

Normally, under JavaScript, this would set or return a number representing the left scroll offset of the element.

See for more information

scrollTop

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

Normally, under JavaScript, this would set or return a number representing number of pixels the top of the document is scrolled vertically.

See for more information

scrollWidth

Read-only

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

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

See for more information

setHTML

Parses and sanitizes a string of HTML and inserts into the DOM as a subtree of the element.

See for more information

shadowRoot

Read-only

Always returns undef

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

See for more information

spellcheck

A boolean value that controls spell-checking. It is present on all HTML elements, though it doesn't have an effect on all of them.

See Mozilla documentation for more information.

style

This does nothing, but return a new empty hash object

Normally, this would set or get A CSSStyleDeclaration representing the declarations of the element's style attribute.

See Mozilla documentation 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

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

textContent

This returns or sets the textual content of an element and all its descendants.

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

title

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

See Mozilla documentation for more information.

translate

A boolean value representing the translation.

See Mozilla documentation 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 element or HTML string in the children list of the element's parent, just after the element.

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

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 element and strings, whereas "appendChild" can only append one element.

See for more information

appendChild

Adds the specified child element argument as the last child to the current element. If the argument referenced 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

attachInternals

This does nothing.

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

See Mozilla documentation for more information.

before

Inserts a set of element or HTML strings in the children list of the element's parent, just before the element.

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

blur

This does nothing.

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

See Mozilla documentation for more information.

click

Sends a mouse click event to the element.

See Mozilla documentation 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

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

contains

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

See for more information

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, this would make the element the current keyboard focus.

See Mozilla documentation 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

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

See for more information

getAttributeNode

Retrieves the node representation of the named attribute from the current node and returns it as an Attr.

Example:

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

See for more information

getAttributeNodeNS

This always returns undef since there is no support for namespace.

Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an Attr.

See for more information

getAttributeNS

This always returns undef since there is no support for namespace.

Retrieves the value of the attribute with the specified namespace and name from the current node and returns it as a string.

See for more information

getElementsByClassName

Provided with a space-delimited list of classes, or a list of classes, and this returns an array object that contains all descendants of the current element that possess the list of classes given in the parameter.

Example:

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

This example finds all elements that have a class of test, which are also a descendant of the element that has the id of main:

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

To find elements whose class lists include both the red and test classes:

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

or, equivalently:

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

Inspecting 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');
});

See for more information

getElementsByTagName

Provided with a tag name, and this returns an array object containing all descendant elements, of a particular tag name, from the current element.

The special string * represents all elements.

Example:

# 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
    }
});

All descendants of the specified element are searched, but not the element itself.

See for more information

getElementsByTagNameNS

This always returns undef since there is 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.

See for more information

getElementsByTagNames

Provided with a space-separated string of tag names, or an array reference of tag names or a list of tag names, and this will return an array object of descendant elements matching those tag names.

This is a non-standard method, courtesy of John Resig

getNextSibling

This non-standard method is an alias for the property "nextSibling"

getPreviousSibling

This non-standard method is an alias for the property "previousSibling"

getRootNode

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

See for more information

hasAttribute

Provided with an attribute name and this returns a boolean value indicating if the element has the specified attribute or not.

Example:

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

See for more information

hasAttributeNS

This always returns undef since there is no support for namespace.

Returns a boolean value indicating if the element has the specified attribute, in the specified namespace, or not.

hasAttributes

Returns a boolean value indicating if the element has one or more HTML attributes present.

Example:

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

See for more information

hasChildNodes

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

See for more information

hidePopover

Experimental

This does nothing.

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

See Mozilla documentation for more information.

insertAdjacentElement

Provided with a position and an element and this inserts a given element node at a given position relative to the element it is invoked upon.

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

It returns a HTML::Object::SyntaxError error if the position specified is not a recognised value.

It returns a HTML::Object::TypeError error if the element specified is not a valid element.

THe position can be any one of (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.

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

See for more information

insertAdjacentHTML

Provided with a position and an element and this parses the text as HTML and inserts the resulting nodes into the tree in the position given.

This takes the same position parameter as "insertAdjacentElement"

It returns the newly created objects from parsing the html data and that were inserted, as an array object, or undef, if the insertion failed.

It returns a HTML::Object::SyntaxError error if the position specified is not a recognised value.

It returns a HTML::Object::TypeError error if the element specified is not 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>

See for more information

insertAdjacentText

Provided with a position and a text string, or a list of text string that will be concatenated, and this inserts the given text at the given position relative to the element it is invoked upon.

This 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 is not a recognised value.

It returns a HTML::Object::TypeError error if the element specified is not 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, the following would fail since there is no data provided:

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

So you have to make sure the data submitted is not zero length.

See for more information

insertBefore

Inserts an element before the reference element as a child of a specified parent element.

See for more information

isDefaultNamespace

Accepts a namespace URI as an argument and returns a boolean value with a value of true if the namespace is the default namespace on the given element or false if not.

See for more information

isEqualNode

Returns a boolean value which indicates 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, defining characteristics (this would be their ID, number of children, and so forth), its attributes match, and so on. The specific set of data points that must match varies depending on the types of the elements.

See for more information

isSameNode

Returns a boolean value indicating whether or not the two elements are the same (that is, they reference the same object).

See for more information

lookupNamespaceURI

Accepts a prefix and returns the namespace URI associated with it on the given element if found (and undef if not). Supplying undef for the prefix will return the default namespace.

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

See for more information

lookupPrefix

This always returns undef.

Returns a string containing the prefix for a given namespace URI, if present, and undef if not.

See for more information

matches

Provided with a CSS selector string, and an optional hash or hash reference, and this returns a boolean value indicating whether or not the element would be selected by the specified selector string.

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

new_attribute

Returns a new HTML::Object::DOM::Attribute object, passing it whatever arguments were provided and return 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 return 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 return 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 return 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 return 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 return 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 return 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 return 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 return 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 return 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, remove empty).

See for more information

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

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 returns a smart undef if nothing is found (to differentiate from an error and still treated as false), and undef upon error and sets an error.

It returns a HTML::Object::SyntaxError error if any of the selector 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

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 selector 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 elment 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

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

removeAttribute

Provided with an attribute name and this removes the attribute with the specified name from the element.

It returns true upon success or false otherwise.

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

Example:

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

See for more information

removeAttributeNode

Provided with an attribute node and this removes the node representation of the named attribute from the current node. This is similar to "removeAttribute", except that "removeAttribute" takes a string as attribute name, while "removeAttributeNode" takes an attribute object.

Upon error, it returns undef and sets an error.

It returns an HTML::Object::SyntaxError if the value 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" />

See for more information

removeAttributeNS

This always return undef since there is no support for namespace.

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

See for more information

removeChild

Removes a child element from the current element, which must be a child of the current element.

See for more information

removeEventListener

Removes an event listener from the element. This 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 parameter.

See for more information

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 nodes provided will be detached from their previous parent and re-attached under the current element.

See for more information

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

See for more information

setAttribute

Provided with a name and a value and 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.

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);

See for more information

setAttributeNode

Provided with an attribute object and this sets, or possibly replace, 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 );

See for more information

setAttributeNodeNS

This always return 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.

See for more information

showPopover

Experimental

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

toggleAttribute

Provided with an attribute name and an optiona force value, and 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");
});

See for more information

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.

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 (also here), nothing prevents you from triggering whatever events you want, even private non-standard ones, and set up listeners for them.

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

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, Mozilla Element documentation

COPYRIGHT & LICENSE

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.