NAME
HTML::Object::DOM::Document - HTML Object DOM Document Class
SYNOPSIS
use HTML::Object::DOM::Document;
my $doc = HTML::Object::DOM::Document->new ||
die( HTML::Object::DOM::Document->error, "\n" );
VERSION
v0.2.2
DESCRIPTION
This module represents an HTML document. It inherits from HTML::Object::Document and HTML::Object::DOM::Element
It is the top object in the hierarchy and thus has no parent. It should contain only one child, the html
element, and has one associated element, the doctype, which can also be accessed with "declaration"
INHERITANCE
+------------------------+ +---------------------------+ +-------------------------+ +----------------------------+ +-----------------------------+
| HTML::Object::Element | --> | HTML::Object::EventTarget | --> | HTML::Object::DOM::Node | --> | HTML::Object::DOM::Element | --> | HTML::Object::DOM::Document |
+------------------------+ +---------------------------+ +-------------------------+ +----------------------------+ +-----------------------------+
| ^
| |
v |
+------------------------+ |
| HTML::Object::Document | -----------------------------------------------------------------------------------------------------------+
+------------------------+
PROPERTIES
activeElement
Normally this returns undef
under perl, but you can set it to whatever element object you want.
Under JavaScript, this returns the element that currently has focus.
See also Mozilla documentation
body
Returns the body
node object of the current document.
Example:
# Given this HTML: <body id="oldBodyElement"></body>
say($doc->body->id); # "oldBodyElement"
my $aNewBodyElement = $doc->createElement("body");
$aNewBodyElement->id = "newBodyElement";
$doc->body = $aNewBodyElement;
say($doc->body->id); # "newBodyElement"
See also Mozilla documentation
characterSet
This is read-only.
Returns the character set being used by the document. This is always utf-8
See also Mozilla documentation
childElementCount
This is read-only.
Returns the number of child elements of the current document. This being the top document, it typically contains only 1 element, the <html
> tag.
The total number of children is not the same as the number of child nodes.
See also Mozilla documentation
children
This is read-only.
Returns the child elements of the current document, as an array object.
See also Mozilla documentation
compatMode
Returns undef
since this is not relevant under perl.
Normally, it would indicate whether the document is rendered in quirks or strict mode.
See also Mozilla documentation
contentType
This is read-only.
Returns the Content-Type from the MIME Header of the current document.
See also Mozilla documentation
cookie
Set or get a semicolon-separated list of the cookies for that document or sets a single cookie.
See also Mozilla documentation
currentScript
Under perl, this does not nor return do anything special, but you can set yourself an HTML::Object::DOM::Element.
Normally, under JavaScript, this returns the currentScript
property returns the <script> element whose script is currently being processed and is not a JavaScript module.
See also Mozilla documentation
defaultView
This returns a reference to the window object.
See also Mozilla documentation
designMode
This always returns true under perl.
Under the web, with JavaScript, this would get/set the ability to edit the whole document.
See also Mozilla documentation
dir
Get or set directionality (rtl/ltr) of the document.
See also Mozilla documentation
doctype
This is read-only.
Returns the Document Type Definition (DTD) object of the current document.
Example:
my $doctypeObj = $doc->doctype;
say(
"doctype->name: " . $doctypeObj->name . "\n" +
"doctype->internalSubset: " . $doctypeObj->internalSubset . "\n" +
"doctype->publicId: " . $doctypeObj->publicId . "\n" +
"doctype->systemId: " . $doctypeObj->systemId
);
See also Mozilla documentation
documentElement
This is read-only.
Returns the element that is a direct child of the document. For HTML documents, this is normally the HTML Element object representing the document's <html
> element.
See also Mozilla documentation
documentURI
Set or get the document location as a string, if any.
See also Mozilla documentation
embeds
This is read-only.
Returns a list, as an html collection object, of the embedded <embed> elements within the current document.
See also Mozilla documentation
featurePolicy
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would return the FeaturePolicy interface which provides a simple API for introspecting the feature policies applied to a specific document.
See also Mozilla documentation
firstElementChild
This is read-only.
Returns the first child element of the current document.
See also Mozilla documentation
fonts
Returns undef
since this is not relevant under perl.
Normally, it would return the FontFaceSet
interface of the current document.
See also Mozilla documentation
forms
This is read-only.
Returns a list, as an html collection object, of the <form> elements within the current document.
See also Mozilla documentation
fullscreenElement
Returns undef
since this is not relevant under perl.
Normally, it would return the element that is currently in full screen mode for this document.
See also Mozilla documentation
head
This is read-only.
Returns the <head element|HTML::Object::DOM::Head> of the current document, or undef
if there is none.
See also Mozilla documentation
hidden
Returns undef
since this is not relevant under perl.
Normally, it would return a boolean value indicating if the page is considered hidden or not.
See also Mozilla documentation
images
This is read-only.
Returns a list, as an html collection object, of the images in the current document.
See also Mozilla documentation
implementation
This returns the DOM implementation object associated with the current document.
See also Mozilla documentation
lastElementChild
This is read-only.
Returns the last child element of the current document, which is the root <html> element, the only child of the document.
See also Mozilla documentation
lastModified
This is read-only.
Returns the date on which the document was last modified, if any, as a DateTime object.
This value exists if the document was read from a file, and it would contain the file last modification time.
See also Mozilla documentation
links
This is read-only.
Returns a list, as an html collection object, of all the hyperlinks in the document.
Example:
my $links = $doc->$links;
for( my $i = 0; $i < $links->length; $i++ )
{
my $linkHref = $doc->createTextNode( $links->[$i]->href );
my $lineBreak = $doc->createElement("br");
$doc->body->appendChild( $linkHref );
$doc->body->appendChild( $lineBreak );
}
See also Mozilla documentation
location
Set or get the URI of the current document. This is the same as "documentURI"
See also Mozilla documentation
mozSyntheticDocument
Normally this is returns undef
under perl, byt you can set whatever boolean value you want.
Under JavaScript, this returns a boolean that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
See also Mozilla documentation
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 returns the objct value.
ownerDocument
Read-only. This always returns undef
since this is the top element. This is inherited from HTML::Object::DOM::Node
pictureInPictureElement
Normally this returns undef
under perl, but you can set whatever element object you want.
Under JavaScript, this returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would return the Element currently being presented in picture-in-picture mode in this document.
See also Mozilla documentation
pictureInPictureEnabled
Normally this returns undef
under perl, but you can set whatever boolean value you want.
Under JavaScript, this would return true if the picture-in-picture feature is enabled, and false otherwise.
See also Mozilla documentation
plugins
Returns always an empty collection object since this is not relevant under perl.
Normally, under JavaScript, this would return a list, as a collection, of the available plugins.
See also Mozilla documentation
pointerLockElement
Normally this returns undef
under perl, but you can set whatever element object you want.
Under JavaScript, this would return the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
See also Mozilla documentation
readyState
This is read-only.
Returns loading status of the document. This always returns a true value.
The readyState of a document can be one of following:
- loading
-
The document is still loading.
- interactive
-
The document has finished loading and the document has been parsed.
There is actually no distinction with the following
complete
state. - complete
-
The document and all its resources have finished loading. The state indicates that the load event is about to fire.
This is actually the same state as
interactive
See also Mozilla documentation
referrer
Set or get the URI of the page that linked to this page.
See also Mozilla documentation
scripts
This is read-only.
Returns all the <script elements|HTML::Object::DOM::Element::Script> on the document, as a collection object.
See also Mozilla documentation
scrollingElement
Although this is meaningless under perl, you can set or get an element object that scrolls the document.
See also Mozilla documentation
styleSheets
This is read-only.
Returns a list, as an array object, of CSS StyleSheet element objects for stylesheets explicitly linked into, or embedded in a document.
Contrary to the original JavaScript equivalent, this does not return CSSStyleSheet
objects, because it would be potentially heavy to parse each css in link
and style
tags. You could do this yourself by using CSS::Object and looping through each element object returned. For example:
$doc->styleSheets->foreach(sub
{
my $e = shift( @_ );
if( $e->tag eq 'link' )
{
my $resp = $ua->get( $e->attr( 'href' ) );
die( $resp->message ) if( $resp->is_error );
my $style = $resp->decoded_content;
my $css = CSS::Object->new;
$css->read_string( $style );
$css->rules->foreach(sub
{
my $rule = shift( @_ );
# more processing
});
}
elsif( $e->tag eq 'style' )
{
my $css = CSS::Object->new;
$css->read_string( $e->text );
$css->rules->foreach(sub
{
my $rule = shift( @_ );
# more processing
});
}
});
or you can use "find" in HTML::Object::XQuery with a xpath selector, such as:
use HTML::Object::XQuery; # Load jQuery style query functions
# $doc is the HTML::Object::Document returned by HTML::Object->parse
my $collection = $doc->find( 'link[rel="https://example.org/css/main.css"]' ) ||
die( $doc->error );
$collection->children->foreach(sub
{
# more processing
});
See also Mozilla documentation
timeline
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would return timeline as a special instance of DocumentTimeline that is automatically created on page load.
See also Mozilla documentation
title
Set or get the title of the current document.
See also Mozilla documentation
URL
Set or get the document location as a string.
See also Mozilla documentation
visibilityState
Normally this returns undef
under perl, but you can set whatever string value you want. This returns a scalar object
Under JavaScript, this would return a string denoting the visibility state of the document. Possible values are visible, hidden, prerender, and unloaded.
See also Mozilla documentation
METHODS
adoptNode
"adoptNode" transfers a node from another document into the method's document. The adopted node and its subtree is removed from its original document (if any), and its ownerDocument is changed to the current document. The node can then be inserted into the current document.
Before they can be inserted into the current document, nodes from external documents should either be:
cloned using "importNode"; or
adopted using "adoptNode".
See also Mozilla documentation
append
Inserts a set of Node objects or string objects after the last child of the document.
This is inherited from HTML::Object::DOM::Element
Example:
my $html = $doc->createElement( 'html' );
$doc->append( $html );
# HierarchyRequestError: The operation would yield an incorrect node tree.
# Also
my $doc = HTML::Object::DOM::Document->new;
my $html = $doc->createElement( 'html');
$doc->append( $html );
$doc->children; # HTMLCollection [<html>]
appendChild
Provided with one or more nodes and this will add them to the list of this document's children.
as_string
Returns a string representation of this document and all its hierarchy.
captureEvents
See "captureEvents" in HTML::Object::DOM::Window.
See also Mozilla documentation
caretRangeFromPoint
Always returns undef
under perl.
See also Mozilla documentation
caretPositionFromPoint
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would return a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node.
See also Mozilla documentation
childNodes
Returns an array object of the document child nodes.
See also Mozilla documentation
close
The close()
method finishes writing to a document, opened with "open".
Example:
# Open a document to write to it
$doc->open();
# Write the content of the document
$doc->write("<p>The one and only content.</p>");
# Close the document
$doc->close();
See also Mozilla documentation
contentType
createAttribute
Provided with an argument and this creates a new attribute object and returns it.
The attribute name is converted to lowercase.
Example:
my $node = $doc->getElementById( 'div1' );
my $a = $doc->createAttribute( 'my_attrib' );
$a->value = 'newVal';
$node->setAttributeNode( $a );
say( $node->getAttribute( 'my_attrib' ) ); # "newVal"
See also Mozilla documentation
createAttributeNS
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would create a new attribute node in a given namespace and returns it.
See also Mozilla documentation
createCDATASection
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would create a new CDATA node and returns it.
See also Mozilla documentation
createComment
Creates a new comment node and returns it.
Example:
my $comment = $doc->createComment( 'This is a not-so-secret comment in your document' );
$doc->getElementsByTagName( 'div' )->[0]->appendChild( $comment );
say( $doc->as_string );
# <div><!--This is a not-so-secret $comment in your document--></div>
See also Mozilla documentation
createDocumentFragment
This create a new HTML::Object::DOM::DocumentFragment object, passing its new()
constructor whatever argument was provided.
It returns the newly instantiated object.
Document fragments are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.
Since the document fragment is not part of the main DOM tree, appending children to it does not affect the main tree.
Example:
<ul id="ul"></ul>
use Module::Generic::Array;
my $element = $doc->getElementById('ul'); # assuming ul exists
my $fragment = $doc->createDocumentFragment();
my $browsers = Module::Generic::Array->new( ['Firefox', 'Chrome', 'Opera',
'Safari', 'Internet Explorer'] );
$browsers->foreach(sub
{
my $browser = shift( @_ );
my $li = $doc->createElement('li');
$li->textContent = $browser;
$fragment->appendChild( $li );
});
$element->appendChild( $fragment );
would yield:
Firefox
Chrome
Opera
Safari
Internet Explorer
createElement
Provided with a tag name and this creates a new HTML::Object::Element object that is returned.
This methods sets an error and returns undef
upon error.
See also Mozilla documentation
createElementNS
Returns undef
since this is not relevant under perl.
Normally, under JavaScript, this would create a new element with the given tag name and namespace URI.
See also Mozilla documentation
createEntityReference
Returns undef
since this is not relevant for HTML document. This is used for XML.
This was used to create a new entity reference object and returns it.
Example:
$doc->createEntityReference( '&' ); # &
See also Mozilla documentation
createEvent
Creates an event object, passing it whatever arguments were provided, and returns it.
Example:
my $event = $doc->createEvent( $type );
# Create the $event.
my $event = $doc->createEvent( 'click' );
# Define that the event name is 'build'.
$event->initEvent( build => { bubbles => 1 });
# Listen for the $event.
$elem->addEventListener( build => sub
{
# e->target matches elem
}, { capture => 0 });
# Target can be any Element or other EventTarget.
$elem->dispatchEvent( $event );
See also Mozilla documentation
createExpression
Compiles an HTML::Object::XPath::Expr which can then be used for (repeated) evaluations. It returns a HTML::Object::DOM::XPathResult object.
Example:
my $xpathExpr = $doc->createExpression( $xpathText );
my $result = $xpathExpr->evaluate( $contextNode );
See also Mozilla documentation
createNSResolver
This always returns undef
as XML is not used in HTML::Object
Normally, under JavaScript, this creates an XPathNSResolver
object.
See also Mozilla documentation
createNodeIterator
Creates a HTML::Object::DOM::NodeIterator object.
Example:
use Module::Generic::Array;
my $nodeIterator = $doc->createNodeIterator(
$doc->body,
NodeFilter->SHOW_ELEMENT,
{
sub acceptNode
{
my $node = shift( @_ );
return( $node->nodeName->toLowerCase() == 'p' ? NodeFilter->FILTER_ACCEPT : NodeFilter->FILTER_REJECT;
}
}
);
my $pars = Module::Generic::Array->new;
my $currentNode;
while( $currentNode = $nodeIterator->nextNode() )
{
$pars->push( $currentNode );
}
See also Mozilla documentation
createProcessingInstruction
Creates a new ProcessingInstruction
object.
Example:
my $doc = HTML::Object::DOM->new->parseFromString('<foo />', 'application/xml');
my $pi = $doc->createProcessingInstruction('xml-stylesheet', 'href="mycss->css" type="text/css"');
$doc->insertBefore($pi, $doc->firstChild);
say( $doc->as_string );
# Displays: <?xml-stylesheet href="mycss->css" type="text/css"?><foo/>
See also Mozilla documentation
createRange
This always returns undef
under perl.
Normally, under JavaScript, this creates a Range
object.
See also Mozilla documentation
createTextNode
Provided with a text, either as a string, or as a list of strings, and this creates a text node.
See also Mozilla documentation
createTouch
This always returns undef
under perl.
Normally, under JavaScript, this creates a Touch object.
Also, this feature is deprecated.
See also Mozilla documentation
createTouchList
This always returns undef
under perl.
Normally, under JavaScript, this creates a TouchList
object.
Also, this feature is deprecated.
See also Mozilla documentation
createTreeWalker
Creates a TreeWalker
object.
Example:
use HTML::Object::DOM::NodeFilter qw( :all );
my $treeWalker = $doc->createTreeWalker(
$doc->body,
SHOW_ELEMENT,
sub{ return( FILTER_ACCEPT ); },
);
my $nodeList = Module::Generic::Array->new;
my $currentNode = $treeWalker->currentNode;
while( $currentNode )
{
$nodeList->push( $currentNode );
$currentNode = $treeWalker->nextNode();
}
See also Mozilla documentation
elementFromPoint
This always returns undef
under perl.
Normally, under JavaScript, this returns the topmost element at the specified coordinates.
See also Mozilla documentation
elementsFromPoint
This always returns undef
under perl.
Normally, under JavaScript, this returns an array of all elements at the specified coordinates.
See also Mozilla documentation
enableStyleSheetsForSet
This always returns undef
under perl.
Normally, under JavaScript, this enables the style sheets for the specified style sheet set.
See also Mozilla documentation
evaluate
Evaluates an XPath expression.
Example:
my $xpathResult = $doc->evaluate(
$xpathExpression,
$contextNode
);
my $headings = $doc->evaluate( "/html/body//h2", $document );
# Search the document for all h2 elements.
# The result will likely be an unordered node iterator.
my $thisHeading = $headings->iterateNext();
my $alertText = "Level 2 $headings in this document are:\n";
while( $thisHeading )
{
$alertText .= $thisHeading->textContent . "\n";
$thisHeading = $headings->iterateNext();
}
say( $alertText ); # print the text of all h2 elements
See also Mozilla documentation
execCommand
This does absolutely nothing and always returns undef
.
This is actually a deprecated feature of the web API.
See also Mozilla documentation
exitPictureInPicture
This always returns undef
under perl.
Normally, under JavaScript, this removes the video from the floating picture-in-picture window back to its original container.
See also Mozilla documentation
exitPointerLock
This always returns undef
under perl.
Normally, under JavaScript, this releases the pointer lock.
See also Mozilla documentation
firstChild
Returns the first child from the document list of nodes.
See also Mozilla documentation
firstElementChild
getElementById
Provided with an element id
, and this method returns the corresponding element object.
See also Mozilla documentation
getAnimations
This always returns undef
under perl.
Normally, under JavaScript, this returns an array of all Animation objects currently in effect, whose target elements are descendants of the document.
See also Mozilla documentation
getBoxQuads
This always returns undef
under perl.
Normally, under JavaScript, this returns a list of DOMQuad
objects representing the CSS fragments of the node.
See also Mozilla documentation
getElementById
Provided with a string and this returns an element object whose id
attribute matches the string specified.
See also Mozilla documentation
getElementsByClassName
Returns a list of elements with the given class name.
Example:
<span class="orange fruit">Orange Fruit</span>
<span class="orange juice">Orange Juice</span>
<span class="apple juice">Apple Juice</span>
<span class="foo bar">Something Random</span>
<textarea id="resultArea" style="width:98%;height:7em"></textarea>
Another example:
# getElementsByClassName only selects elements that have both given classes
my $allOrangeJuiceByClass = $doc->getElementsByClassName('orange juice');
my $result = "$doc->getElementsByClassName('orange juice')";
for( my $i=0; $i < $allOrangeJuiceByClass->length; $i++ )
{
$result .= "\n " . $allOrangeJuiceByClass->[$i]->textContent;
}
# querySelector only selects full complete matches
my $allOrangeJuiceQuery = $doc->querySelectorAll('.orange->juice');
$result += "\n\ndocument->querySelectorAll('.orange->juice')";
for( my $i=0; $i < $allOrangeJuiceQuery->length; $i++ )
{
$result .= "\n " . $allOrangeJuiceQuery->[$i]->textContent;
}
$doc->getElementById( 'resultArea' )->value = $result;
See also Mozilla documentation
getElementsByName
Returns a NodeList Collection of elements with a given name attribute in the document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example: using getElementsByName</title>
</head>
<body>
<input type="hidden" name="up" />
<input type="hidden" name="down" />
</body>
</html>
my $up_names = $doc->getElementsByName( 'up' );
say( $up_names->[0]->tagName ); # displays "input"
See also Mozilla documentation
getElementsByTagName
Returns a list of elements with the given tag name.
See also Mozilla documentation
getElementsByTagNameNS
This is merely an alias to "getElementsByTagName" since there is no support for namespace.
Normally, under JavaScript, this returns a list of elements with the given tag name and namespace.
See also Mozilla documentation
getRootNode
Returns the current object.
getSelection
This always returns undef
under perl.
Normally, under JavaScript, this returns a Selection
object representing the range of text selected by the user, or the current position of the caret.
See also Mozilla documentation
hasChildNodes
Returns true if the document list of nodes is not empty, false otherwise.
See also Mozilla documentation
hasFocus
Under perl, this always returns true.
Normally, under JavaScript, this returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.
See also Mozilla documentation
hasStorageAccess
This always returns undef
under perl.
Normally, under JavaScript, this returns a Promise
that resolves with a boolean value indicating whether the document has access to its first-party storage.
See also Mozilla documentation
importNode
Returns a clone of a node from an external document.
Example:
my $iframe = $doc->querySelector( 'iframe' );
my $oldNode = $iframe->contentWindow->document->getElementById( 'myNode' );
my $newNode = $doc->importNode( $oldNode, $true );
$doc->getElementById( 'container' )->appendChild( $newNode );
See also Mozilla documentation
insertAfter
Provided with a node and a reference node and this will insert the node after the reference node.
It returns the current object upon success, or undef
upon error
Surprisingly enough there is no insertAfter
method in the web API, only "insertBefore"
insertBefore
Provided with a node and a reference node and this will insert the node before the reference node.
It returns the current object upon success, or undef
upon error
See also Mozilla documentation
lastChild
Returns the last child node from the document list of nodes.
See also Mozilla documentation
mozSetImageElement
This always returns undef
under perl.
Normally, under JavaScript, this allows you to change the element being used as the background image for a specified element ID.
See also Mozilla documentation
nextSibling
Returns a smart undef. This means the return value will depend on what the caller expects. In scalar context it will return undef
and an empty list in list context, but if this method is chained, it will return a dummy object to avoid the perl error "method called on an undefined value"
See also Mozilla documentation
normalizeDocument
Replaces entities, normalizes text nodes, etc.
This is actually an alias to "normalize" in HTML::Object::DOM::Node
See also Mozilla documentation
open
The open()
method opens a document for writing and returns the current document object.
This does come with some side effects. For example:
All event listeners currently registered on the document, nodes inside the document, or the document's window are removed.
Example:
The following simple code opens the document and replaces its content with a number of different HTML fragments, before closing it again.
my $doc = $parser->parse_data( $html );
$doc->open();
$doc->write("<p>Hello world!</p>");
$doc->write("<p>I am a fish</p>");
$doc->write("<p>The number is 42</p>");
$doc->close();
An automatic "open" call happens when "write" is called after the document has loaded.
See also Mozilla documentation
parentElement
This interface returns the DOM node's parent Element, or undef
if the node either has no parent, or its parent isn't a DOM Element.
See also Mozilla documentation
parentNode
This returns the parent of the specified node in the DOM tree.
Document and DocumentFragment nodes can never have a parent, so parentNode
will always return undef
.
See also Mozilla documentation
prepend
Inserts a set of Node objects or string objects before the first child of the document.
Example:
my $html = $doc->createElement( 'html' );
$doc->prepend( $html );
# HierarchyRequestError: The operation would yield an incorrect node tree.
Another example:
my $doc = HTML::Object::DOM::Document->new;
my $html = $doc->createElement( 'html' );
$doc->prepend( $html );
$doc->children; # HTMLCollection [<$html>]
See also Mozilla documentation
previousSibling
This returns the node immediately preceding the specified one in its parent's childNodes list, or undef
if the specified node is the first in that list.
See also Mozilla documentation
queryCommandEnabled
This always returns false under perl.
Normally, under JavaScript, this reports whether or not the specified editor command is enabled by the browser.
See also Mozilla documentation
queryCommandIndeterm
This always returns true under perl.
Normally, under JavaScript, this returns true if the formatting command is in an indeterminate state on the current range.
See also Mozilla documentation
queryCommandState
This always returns false under perl.
Normally, under JavaScript, this returns true if the formatting command has been executed on the current range.
See also Mozilla documentation
queryCommandSupported
This always returns false under perl.
Normally, under JavaScript, this returns true if the formatting command is supported on the current range.
See also Mozilla documentation
queryCommandValue
This always returns undef
under perl.
Normally, under JavaScript, this returns the current value of the current range for a formatting command.
See also Mozilla documentation
querySelector
Returns the first Element node within the document, in document order, that matches the specified selectors.
Example:
<div id="foo\bar"></div>
<div id="foo:bar"></div>
$doc->querySelector( '#foo\\bar' ); # Match the first div
$doc->querySelector( '#foo\:bar' ); # Match the second div
my $el = $doc->querySelector(".myclass");
See also Mozilla documentation
querySelectorAll
Returns a list of all the Element nodes within the document that match the specified selectors.
Example:
<div class="outer">
<div class="select">
<div class="inner">
</div>
</div>
</div>
my $inner = $select->querySelectorAll( '.outer .inner' );
$inner->length; # 1, not 0
See also Mozilla documentation
releaseCapture
Releases the current mouse capture if it's on an element in this document.
See also Mozilla documentation
releaseEvents
See "releaseEvents" in HTML::Object::DOM::Window.
See also Mozilla documentation
removeChild
Provided with a node and this removes a child node from the DOM and returns the removed node.
See also Mozilla documentation
replaceChild
Provided with a new
node and and an old
node and this will replace the old
one by the new
one. Note that if the new
node is already present somewhere else in the DOM
, it is first removed from that position.
This returns the old
node removed.
See the document in "replaceChild" in HTML::Object::DOM::Node for more details.
See also Mozilla documentation
replaceChildren
Replaces the existing children of a document with a specified new set of children.
Example:
$doc->replaceChildren();
$doc->children; # HTMLCollection []
See also Mozilla documentation
requestStorageAccess
This always returns undef
under perl.
Normally, under JavaScript, this returns a Promise
that resolves if the access to first-party storage was granted, and rejects if access was denied.
See also Mozilla documentation
string_value
This always return undef
.
write
Provided with a list of nodes and this will write them to the body of this document. If the document is already closed, such as when it has already loaded, this will call "open", which will cause to empty the document.
See also Mozilla documentation
writeln
Same as with "write", except this will add a new line.
See also Mozilla documentation
EVENTS
There is only limited support for events under perl, but you can trigger yourself any event.
Event listeners for those events can also be found by prepending on
before the event type:
click
event listeners can be set also with onclick
method:
$e->onclick(sub{ # do something });
# or as an lvalue method
$e->onclick = sub{ # do something };
Below are some key ones, but you can see the full lists on the Mozilla documentation
DOMContentLoaded
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
See also Mozilla documentation
readystatechange
Fired when the readyState attribute of a document has changed.
See also Mozilla documentation
visibilitychange
Fired when the content of a tab has become visible or has been hidden. Also available via the onvisibilitychange property.
See also Mozilla documentation
EVENT HANDLERS
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::DOM::Document and for the others, nothing prevents you from triggering whatever events you want on any element, even private non-standard ones, and set up listeners for them.
Below are the ones actually "fired" by HTML::Object.
onabort
This takes a code reference (a reference to a subroutine or an anonymous subroutine) as its unique argument.
The onabort
property is the event handler for processing abort
events sent to the perl script.
It returns undef
and sets an HTML::Object::TypeError
error if the value provided is not a code reference, i.e. a reference to an existing subroutine or an anonymous subroutine.
It returns true upon success.
Upon an abort signal (ABRT
, INT
or TERM
), this will execute the code reference, passing it an error event object
Example:
use HTML::Object::DOM;
my $p = HTML::Object::DOM->new;
$doc = $p->parse_data( $some_html_string );
$doc->onabort = sub
{
my $event = shift( @_ );
print( "Oh no: ", $event->trace, "\n" );
};
# or
$doc->onabort = \&exception_handler;
onafterscriptexecute
Under perl, no such event is fired, but you can trigger one yourself.
This property references a function that fires when a static <script> element finishes executing its script. It does not fire if the element is added dynamically, such as with appendChild().
See also Mozilla documentation
onbeforescriptexecute
Under perl, no such event is fired, but you can trigger one yourself.
This is fired when the code in a <script> element declared in an HTML document is about to start executing. Does not fire if the element is added dynamically, eg with appendChild().
See also Mozilla documentation
oncopy
Under perl, no such event is fired, but you can trigger one yourself.
This represents the event handling code for the copy event.
See also Mozilla documentation
oncut
Under perl, no such event is fired, but you can trigger one yourself.
This represents the event handling code for the cut event.
See also Mozilla documentation
onerror
The onerror
property is an event handler that processes error events triggered by a "warn" in perlfunc or "die" in perlfunc
Upon an error signal (__WARN__
, or __DIE__
), this will execute the code reference, passing it an error event object
Example:
use HTML::Object::DOM;
my $p = HTML::Object::DOM->new;
$doc = $p->parse_data( $some_html_string );
$doc->onerror = sub
{
my $event = shift( @_ );
print( "Oh no: ", $event->trace, "\n" );
};
# or
$doc->onerror = \&exception_handler;
onfullscreenchange
Under perl, no such event is fired, but you can trigger one yourself.
This property is an event handler for the fullscreenchange event that is fired immediately before a document transitions into or out of full-screen mode.
See also Mozilla documentation
onfullscreenerror
Under perl, no such event is fired, but you can trigger one yourself.
This property is an event handler for the fullscreenerror event that is sent to the document when it fails to transition into full-screen mode after a prior call to Element.requestFullscreen().
See also Mozilla documentation
onload
The onload
property is an event handler for the load
event that fires when the initial HTML document has been completely loaded and parsed. It is fired after the "readyState" has changed to complete
Contrary to the JavaScript environment, under perl, there is obviously no window and thus no difference between the JavaScript window load event and the DOMContentLoaded event
For example:
$doc->addEventListener( load => sub
{
say( 'Document fully loaded and parsed' );
});
sub doSomething
{
say( 'Document loaded' );
}
# Loading has not finished yet
if( $doc->readyState eq 'loading' )
{
$doc->addEventListener( load => \&doSomething );
}
# 'load' has already fired
else
{
doSomething();
}
Upon execution, a new event is passed of type readstate
and with the detail
property having the following data available:
- document
-
The document object
- state
-
The state of the document parsing.
The event target
property is also set to the document object.
onpaste
Under perl, no such event is fired, but you can trigger one yourself.
This property interface is an event handler that processes paste events.
The paste event fires when the user attempts to paste text.
See also Mozilla documentation
onreadystatechange
The onreadystatechange
property is an event handler for the readystatechange
event that is fired when the "readyState" attribute of a document has changed.
There are 3 state: loading
, interactive
and complete
(which is the same, under perl, as loading
)
This event does not bubble and is not cancelable
Upon execution, a new event is passed of type readstate
and with the detail
property having the following data available:
- document
-
The document object
- state
-
The state of the document parsing.
The event target
property is also set to the document object.
onscroll
Under perl, no such event is fired, but you can trigger one yourself.
This property interface is an event handler that processes events when the document view or an element has been scrolled, whether by the user, a Web API, or the user agent.
See also Mozilla documentation
onselectionchange
Under perl, no such event is fired, but you can trigger one yourself.
This is fired when the Selection of a Document is changed. The Selection consists of a starting position and (optionally) a range of HTML nodes from that position. Clicking or starting a selection outside of a text field will generally fire this event.
See also Mozilla documentation
onvisibilitychange
Is an event handler representing the code to be called when the visibilitychange event is raised.
See also Mozilla documentation
onwheel
Under perl, no such event is fired, but you can trigger one yourself.
This event is fired when the user rotates the mouse (or other pointing device) wheel.
See also Mozilla documentation
AUTHOR
Jacques Deguest <jack@deguest.jp>
SEE ALSO
HTML::Object::Document, HTML::Object::DOM::Element
Mozilla documentation on DOM, Mozilla documentation on Document object
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.