blib/lib/HTML/Object/DOM/Node.pm untested

filter: Statementstmt 0.0% 0 / 600 Branchbran 0.0% 0 / 260 Conditioncond 0.0% 0 / 246 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 78 Podpod 0.0% 0 / 68 totaltotal 0.0% 0 / 1252 CC 131 SCAR 51.2
CC
131
Cov
0%
compareDocumentPosition
812.0
replaceChild
306.0
appendChild
182.0
CRAP 166.9
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/DOM/Node.pm
3 ## Version v0.3.0_1
4 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/12/13
7 ## Modified 2026/03/29
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object::DOM::Node;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 use parent qw( HTML::Object::EventTarget );
21 use vars qw( @EXPORT $XP $VERSION );
22 use Wanted;
23 use constant {
24 DOCUMENT_POSITION_IDENTICAL => 0,
25 DOCUMENT_POSITION_DISCONNECTED => 1,
26 DOCUMENT_POSITION_PRECEDING => 2,
27 DOCUMENT_POSITION_FOLLOWING => 4,
28 DOCUMENT_POSITION_CONTAINS => 8,
29 DOCUMENT_POSITION_CONTAINED_BY => 16,
30 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC => 32,
31 XML_DEFAULT_NAMESPACE => 'http://www.w3.org/XML/1998/namespace',
32 ELEMENT_NODE => 1,
33 ATTRIBUTE_NODE => 2,
34 TEXT_NODE => 3,
35 CDATA_SECTION_NODE => 4,
36 # Deprecated
37 ENTITY_REFERENCE_NODE => 5,
38 # Deprecated
39 ENTITY_NODE => 6,
40 PROCESSING_INSTRUCTION_NODE => 7,
41 COMMENT_NODE => 8,
42 DOCUMENT_NODE => 9,
43 DOCUMENT_TYPE_NODE => 10,
44 DOCUMENT_FRAGMENT_NODE => 11,
45 NOTATION_NODE => 12,
46 SPACE_NODE => 13,
47 };
48 our @EXPORT = qw(
49 DOCUMENT_POSITION_IDENTICAL
50 DOCUMENT_POSITION_DISCONNECTED
51 DOCUMENT_POSITION_PRECEDING
52 DOCUMENT_POSITION_FOLLOWING
53 DOCUMENT_POSITION_CONTAINS
54 DOCUMENT_POSITION_CONTAINED_BY
55 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
56
57 ELEMENT_NODE
58 ATTRIBUTE_NODE
59 TEXT_NODE
60 CDATA_SECTION_NODE
61 ENTITY_REFERENCE_NODE
62 ENTITY_NODE
63 PROCESSING_INSTRUCTION_NODE
64 COMMENT_NODE
65 DOCUMENT_NODE
66 DOCUMENT_TYPE_NODE
67 DOCUMENT_FRAGMENT_NODE
68 NOTATION_NODE
69 SPACE_NODE
70 );
71 use overload (
72 '==' => \&isSameNode,
73 'eq' => \&isSameNode,
74 );
75 our $XP;
76 our $VERSION = 'v0.3.0_1';
77 };
78  
79 use strict;
80 use warnings;
81  
82 sub init
83 {
84 my $self = shift( @_ );
85 $self->{_init_strict_use_sub} = 1;
86 $self->HTML::Object::Element::init( @_ ) || return( $self->pass_error );
87 return( $self );
88 }
89  
90 sub appendChild
91 {
92 my $self = shift( @_ );
93 return( $self->error({
94 message => sprintf( "At least 1 arguments is required, but only %d provided.", scalar( @_ ) ),
95 class => 'HTML::Object::TypeError',
96 }) ) if( scalar( @_ ) < 1 );
97 my $new = shift( @_ );
98 my $new_parent = $new->parent;
99 my $parent = $self->parent;
100 # We use 'nodes' rather than 'children' so this works well with HTML::Object::DOM::Document
101 my $nodes = $self->nodes;
102 if( $new_parent &&
103 !$self->_is_a( $new_parent => 'HTML::Object::DOM::Document' ) &&
104 !$self->_is_a( $new_parent => 'HTML::Object::DOM::DocumentFragment' ) &&
105 !$self->_is_a( $new_parent => 'HTML::Object::DOM::Element' ) )
106 {
107 return( $self->error({
108 message => "Node's parent is not an HTML::Object::DOM::Document, HTML::Object::DOM::DocumentFragment or HTML::Object::DOM::Element object.",
109 class => 'HTML::Object::HierarchyRequestError',
110 }) );
111 }
112 # All other conditions below are strictly similar to replaceChild()
113 elsif( !$self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) &&
114 !$self->_is_a( $new => 'HTML::Object::DOM::Declaration' ) &&
115 !$self->_is_a( $new => 'HTML::Object::DOM::Element' ) &&
116 !$self->_is_a( $new => 'HTML::Object::DOM::CharacterData' ) )
117 {
118 return( $self->error({
119 message => "New node is not an HTML::Object::DOM::DocumentFragment, HTML::Object::DOM::Declaration, HTML::Object::DOM::Element or HTML::Object::DOM::CharacterData object.",
120 class => 'HTML::Object::HierarchyRequestError',
121 }) );
122 }
123 elsif( $self->lineage->has( $new ) )
124 {
125 return( $self->error({
126 message => "New node provided is an ancestor of the current node.",
127 class => 'HTML::Object::HierarchyRequestError',
128 }) );
129 }
130 elsif( ( $self->_is_a( $new => 'HTML::Object::DOM::Text' ) || $self->_is_a( $new => 'HTML::Object::DOM::Space' ) ) &&
131 $self->_is_a( $new_parent => 'HTML::Object::DOM::Document' ) )
132 {
133 return( $self->error({
134 message => "New node is a HTML::Object::DOM::Text or HTML::Object::DOM::Space node and its parent is a HTML::Object::DOM::Document node.",
135 class => 'HTML::Object::HierarchyRequestError',
136 }) );
137 }
138 elsif( $self->isa( 'HTML::Object::DOM::Declaration' ) && !$self->_is_a( $parent => 'HTML::Object::DOM::Document' ) )
139 {
140 return( $self->error({
141 message => "Current node is a DocumentType, but its parent is not an HTML::Object::DOM::Document object.",
142 class => 'HTML::Object::HierarchyRequestError',
143 }) );
144 }
145 elsif( $self->_is_a( $parent => 'HTML::Object::DOM::Document' ) &&
146 $self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) &&
147 ( $new->childElementCount > 1 || $new->children->grep(sub{ $self->_is_a( $_ => 'HTML::Object::DOM::Text' ) })->length ) )
148 {
149 return( $self->error({
150 message => "Current node parent is a HTML::Object::DOM::Document object and new node is a HTML::Object::DOM::DocumentFragment object that has either more than 1 element or has a HTML::Object::DOM::Text node.",
151 class => 'HTML::Object::HierarchyRequestError',
152 }) );
153 }
154 # This is different from replaceChild()
155 elsif( $self->_is_a( $parent => 'HTML::Object::DOM::Document' ) &&
156 $parent->childElementCount > 0 &&
157 $self->_is_a( $new => 'HTML::Object::DOM::Element' ) )
158 {
159 return( $self->error({
160 message => "Attempting to replace a child element in a Document with another non HTML-tag element. Document can have only one Element: the HTML-tag element.",
161 class => 'HTML::Object::HierarchyRequestError',
162 }) );
163 }
164 # If the node to append is a doctype and the curent last node is an element, this would put a doctype after an element, which is forbidden
165 elsif( $self->_is_a( $new => 'HTML::Object::DOM::Declaration' ) &&
166 $self->_is_a( $nodes->last, 'HTML::Object::DOM::Element' ) )
167 {
168 return( $self->error({
169 message => "The last node is an element. Appending the DocumentType would place it after.",
170 class => 'HTML::Object::HierarchyRequestError',
171 }) );
172 }
173  
174 $new->detach;
175 my $new_array = $self->new_array( $self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) ? $new->children : $new );
176 $new_array->foreach(sub
177 {
178 return(1) if( !$self->_is_a( $_ => 'HTML::Object::DOM::Node' ) );
179 $_->parent( $self );
180 });
181 $nodes->push( $new_array->list );
182 $self->reset(1);
183 if( $self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) )
184 {
185 $new->children->reset;
186 }
187 return( $new );
188 }
189  
190 sub appendNodes
191 {
192 my $self = shift( @_ );
193 my $children = $self->children;
194 foreach my $this ( @_ )
195 {
196 if( $self->_is_a( $this => 'HTML::Object::DOM::Node' ) )
197 {
198 $this->parent( $self );
199 $children->push( $this );
200 }
201 }
202 return( $self );
203 }
204  
205 # Note: Property
206 # Example: <base href="https://www.example.com/">
207 sub baseURI : lvalue { return( shift->_set_get_callback({
208 get => sub
209 {
210 my $self = shift( @_ );
211 my $root = $self->root;
212 return( $self->new_null ) if( !$root );
213 return( $self->new_null ) if( !$root->can( 'uri' ) );
214 return( $root->uri ) if( $root->uri );
215 my $nodes = $self->findNode( 'base' );
216 return( $self->new_null ) if( $nodes->is_empty );
217 my $node = $nodes->first;
218 return( $self->new_null ) if( !$node );
219 return( $self->new_null ) if( !$node->attributes->has( 'href' ) );
220 my $uri = $node->attributes->get( 'href' );
221 return( $self->new_null ) if( !defined( $uri ) || !CORE::length( "$uri" ) );
222 return( $self->_set_get_uri( 'uri', $uri ) );
223 },
224 set => sub
225 {
226 my $self = shift( @_ );
227 my $uri = shift( @_ );
228 my $root = $self->root;
229 return( $self->new_null ) if( !$root );
230 my $nodes = $root->findNode( 'base' );
231 my $base;
232 if( $nodes->is_empty )
233 {
234 $base = $root->createElement( 'base' ) || return( $self->error( $root->pass_error ) );
235 my $head = $root->findNode( 'head' )->first ||
236 return( $self->error( "No base uri can be set, because there is no head element in this document." ) );
237 $head->appendChild( $base );
238 }
239 else
240 {
241 $base = $nodes->first;
242 }
243 $base->href( $uri ) || return( $self->error( $base->pass_error ) );
244 return( $uri );
245 },
246 }, @_ ) ); }
247  
248 sub childNodes { return( shift->children ); }
249  
250 sub cloneNode
251 {
252 my $self = shift( @_ );
253 my $clone = $self->clone;
254 $clone->parent( undef );
255 return( $clone );
256 }
257  
258 sub compareDocumentPosition
259 {
260 my $self = shift( @_ );
261 my $elem = shift( @_ ) || return( $self->error( "No element was provided to append." ) );
262 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is actually not an HTML element." ) ) if( !$self->_is_a( $elem => 'HTML::Object::Element' ) );
263 # 0 - Elements are identical.
264 # -> DOCUMENT_POSITION_IDENTICAL
265 # 1 - No relationship, both nodes are in different documents or different trees in the same document.
266 # -> DOCUMENT_POSITION_DISCONNECTED
267 # 2 - The specified node precedes the current node.
268 # otherNode precedes the node in either a pre-order depth-first traversal of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
269 # -> DOCUMENT_POSITION_PRECEDING
270 # 4 - The specified node follows the current node.
271 # The otherNode follows the node in either a pre-order depth-first traversal of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
272 # -> DOCUMENT_POSITION_FOLLOWING
273 # 8 - The otherNode is an ancestor of / contains the current node.
274 # -> DOCUMENT_POSITION_CONTAINS
275 # 16 - The otherNode is a descendant of / contained by the node.
276 # -> DOCUMENT_POSITION_CONTAINED_BY
277 # 32 - The specified node and the current node have no common container node or the two nodes are different attributes of the same node.
278 # -> DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
279
280 # "If the two nodes being compared are the same node, then no flags are set on the return."
281 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
282 return(0) if( Scalar::Util::refaddr( $self ) eq Scalar::Util::refaddr( $elem ) );
283 # Current object and other element are both attributes of the same element (ownerElement)
284 # "If neither of the two determining node is a child node and nodeType is the same for both determining nodes, then an implementation-dependent order between the determining nodes is returned."
285 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
286 if( $self->nodeType == ATTRIBUTE_NODE && $elem->nodeType == ATTRIBUTE_NODE )
287 {
288 # 2 attributes of the same node
289 return(32) if( $self->ownerElement && $self->ownerElement eq $elem->ownerElement );
290 }
291
292 my $parent = $self->parent;
293 my $parent2 = $elem->parent;
294 # "If neither of the two determining node is a child node and one determining node has a greater value of nodeType than the other, then the corresponding node precedes the other."
295 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
296 if( !$parent && !$parent2 )
297 {
298 return( $self->nodeType < $elem->nodeType ? DOCUMENT_POSITION_FOLLOWING : DOCUMENT_POSITION_PRECEDING );
299 }
300
301 my $root = $self->root;
302 my $root2 = $elem->root;
303 # Both elements are in different documents
304 if( $root ne $root2 )
305 {
306 return( DOCUMENT_POSITION_DISCONNECTED );
307 }
308
309 my $bit = 0;
310 my $lineage = $self->lineage;
311 my $lineage2 = $elem->lineage;
312 my $prev_siblings = $self->left;
313 my $next_siblings = $self->right;
314 my $seen = {};
315 my $crawl;
316 $crawl = sub
317 {
318 my $kid = shift( @_ );
319 my $addr = Scalar::Util::refaddr( $kid );
320 return if( ++$seen->{ $addr } > 1 );
321 my $children = $kid->children;
322 foreach( @$children )
323 {
324 if( $_->can( 'eid' ) &&
325 defined( $_->eid ) &&
326 defined( $elem->eid ) &&
327 $_->eid eq $elem->eid )
328 {
329 return( $_ );
330 }
331 if( my $e = $crawl->( $_ ) )
332 {
333 return( $e );
334 }
335 }
336 return;
337 };
338
339 # Check if our parent is among the other element's parents
340 my $parent_pos = $lineage2->pos( $parent );
341 # Check if the other element's parent is among our parents
342 my $parent2_pos = $lineage->pos( $parent2 );
343 # Then check their position, if found
344 if( defined( $parent_pos ) && defined( $parent2_pos ) )
345 {
346 if( $parent_pos > $parent2_pos )
347 {
348 $bit |= DOCUMENT_POSITION_FOLLOWING;
349 }
350 elsif( $parent2_pos > $parent_pos )
351 {
352 $bit |= DOCUMENT_POSITION_PRECEDING;
353 }
354 else
355 {
356 # Nodes share the same parent, and thus are siblings
357 }
358 }
359 elsif( defined( $parent_pos ) )
360 {
361 $bit |= DOCUMENT_POSITION_FOLLOWING;
362 }
363 elsif( defined( $parent2_pos ) )
364 {
365 $bit |= DOCUMENT_POSITION_PRECEDING;
366 }
367 # Otherwise neither our parent or the other's parent is in either lineage
368 else
369 {
370 # Neither our parent, nor the other's parent is in either lineage.
371 }
372
373 if( $lineage->intersection( $lineage2 )->is_empty &&
374 $lineage2->intersection( $lineage )->is_empty )
375 {
376 $bit |= DOCUMENT_POSITION_DISCONNECTED;
377 }
378 else
379 {
380 # Our lineage or the other or both lineages intersect
381 }
382 # Check for the other node in:
383 # 1) ancestor
384 # 2) previous sibling
385 # 3) descendant of previous sibling
386 # 4) previous sibling of an ancestor
387
388 # "If one of the nodes being compared contains the other node, then the container precedes the contained node, and reversely the contained node follows the container."
389 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
390 if( $lineage->has( $elem ) )
391 {
392 $bit |= DOCUMENT_POSITION_PRECEDING;
393 $bit |= DOCUMENT_POSITION_CONTAINS;
394 }
395 # check previous sibling
396 elsif( $prev_siblings->has( $elem ) )
397 {
398 $bit |= DOCUMENT_POSITION_PRECEDING;
399 }
400 else
401 {
402 # check for descendant of previous sibling
403 $seen = {};
404 foreach( @$prev_siblings )
405 {
406 if( my $e = $crawl->( $_ ) )
407 {
408 $bit |= DOCUMENT_POSITION_PRECEDING;
409 last;
410 }
411 }
412  
413 # no luck so far. Checking previous sibling of an ancestor
414 if( !( $bit & DOCUMENT_POSITION_PRECEDING ) )
415 {
416 # Go through each ancestor
417 foreach( @$lineage )
418 {
419 # then get its previous siblings
420 my $ancestor_siblings = $_->left;
421 # and check if the other element is one of them
422 if( $ancestor_siblings && $ancestor_siblings->has( $elem ) )
423 {
424 $bit |= DOCUMENT_POSITION_PRECEDING;
425 last;
426 }
427 }
428 }
429 }
430
431 # still no luck, check
432 # 1) descendants
433 # 2) following sibling
434 # 3) a descendant of a following sibling
435 # 4) following sibling of an ancestor
436 $seen = {};
437 # e.g. a child or an attribute of our element:
438 # "when comparing an element against its own attribute or child, the element node precedes its attribute node and its child node, which both follow it."
439 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
440 if( $lineage2->has( $self ) )
441 {
442 $bit |= ( DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING )
443 }
444 # Now check for following siblings
445 elsif( $next_siblings->has( $elem ) )
446 {
447 $bit |= DOCUMENT_POSITION_FOLLOWING;
448 }
449 # "If one of the nodes being compared contains the other node, then the container precedes the contained node, and reversely the contained node follows the container."
450 # <https://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
451 # We look deeper than our direct child
452 elsif( my $e = $crawl->( $self ) )
453 {
454 $bit |= ( DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING )
455 }
456 # check for a descendant of a following sibling
457 else
458 {
459 $seen = {};
460 foreach( @$next_siblings )
461 {
462 if( my $e = $crawl->( $_ ) )
463 {
464 $bit |= DOCUMENT_POSITION_FOLLOWING;
465 last;
466 }
467 }
468
469 # no luck so far. Checking previous sibling of an ancestor
470 if( !( $bit & DOCUMENT_POSITION_FOLLOWING ) )
471 {
472 # Go through each ancestor
473 foreach( @$lineage )
474 {
475 # then get its following siblings
476 my $ancestor_siblings = $_->right;
477 # and check if the other element is one of them
478 if( $ancestor_siblings && $ancestor_siblings->has( $elem ) )
479 {
480 $bit |= DOCUMENT_POSITION_PRECEDING;
481 last;
482 }
483 }
484 }
485 }
486 return( $bit );
487 }
488  
489 sub contains
490 {
491 my $self = shift( @_ );
492 my $elem = shift( @_ ) || return( $self->error( "No element was provided to append." ) );
493 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is actually not an HTML element." ) ) if( !$self->_is_a( $elem => 'HTML::Object::Element' ) );
494 # Object and comparison object are the same
495 return(1) if( Scalar::Util::refaddr( $self ) eq Scalar::Util::refaddr( $elem ) );
496 my $found = 0;
497 my $seen = {};
498 my $traverse;
499 $traverse = sub
500 {
501 my $e = shift( @_ );
502 return if( !defined( $e ) || !CORE::length( $e ) );
503 my $addr = Scalar::Util::refaddr( $e );
504 return if( CORE::exists( $seen->{ $addr } ) );
505 $seen->{ $addr }++;
506 $e->children->foreach(sub
507 {
508 if( $_->eid eq $elem->eid )
509 {
510 $found++;
511 return(1);
512 }
513 return( $traverse->( $_ ) );
514 });
515 };
516 $traverse->( $self );
517 return( $found );
518 }
519  
520 # Takes a selector; or
521 # Element object
522 # We alias find to findNode(), because find(9 get redefined by HTML::Object::XQuery and
523 # we need internally to continue to rely on this method
524 sub find { return( shift->findNode( @_ ) ); }
525  
526 sub find_xpath
527 {
528 my( $self, $path ) = @_;
529 return( $self->xp->find( $path, $self ) );
530 }
531  
532 sub findNode
533 {
534 my $self = shift( @_ );
535 my $this = shift( @_ );
536 my $opts = $self->_get_args_as_hash( @_ );
537 my $results = $self->new_array;
538
539 if( ref( $this ) && $self->_is_object( $this ) && $this->isa( 'HTML::Object::DOM::Element' ) )
540 {
541 my $a = $self->new_array( [ $this ] );
542 my $lookup;
543 $lookup = sub
544 {
545 my $kids = shift( @_ );
546 $kids->foreach(sub
547 {
548 my $child = shift( @_ );
549 $a->foreach(sub
550 {
551 my $candidate = shift( @_ );
552 if( $child->eid eq $candidate->eid )
553 {
554 $results->push( $child );
555 # We've added this child. Move to next child.
556 return(1);
557 }
558 });
559 if( $child->children->length > 0 )
560 {
561 $lookup->( $child->children );
562 }
563 });
564 };
565 # Wether this is a collection or just an element object, we check our children
566 $lookup->( $self->children );
567 }
568 # I am expecting an xpath value
569 else
570 {
571 if( ref( $this ) &&
572 (
573 !overload::Overloaded( $this ) ||
574 ( overload::Overloaded( $this ) && !overload::Method( $this, '""' ) )
575 ) )
576 {
577 return( $self->error( "I was expecting an xpath string, but instead I got '$this'." ) );
578 }
579 my $xpath = $self->_xpath_value( $this, $opts ) || return( $self->pass_error );
580 # $self->children->foreach(sub
581 # {
582 # my $child = shift( @_ );
583 # return(1) if( !$child->isElementNode );
584 # # Propagate debug value
585 # $child->debug( $self->debug );
586 # try
587 # {
588 # my @nodes = $child->findnodes( $xpath );
589 # # $self->messagef( 4, "%d nodes found under child element '$child' whose tag is '%s' -> '%s'", scalar( @nodes ), $child->tag, join( "', '", map( overload::StrVal( $_ ), @nodes ) ) );
590 # $results->push( @nodes );
591 # }
592 # catch( $e )
593 # {
594 # warn( "Error while calling findnodes on element id \"", $_->id, "\" and tag \"", $_->tag, "\": $e\n" );
595 # }
596 # });
597 # try-catch
598 local $@;
599 eval
600 {
601 my @nodes = $self->findnodes( $xpath );
602 $results->push( @nodes );
603 };
604 if( $@ )
605 {
606 warn( "Error while calling findnodes on element with tag \"", ( $self->tag // '' ), "\": $@\n" );
607 }
608 }
609 return( $results );
610 }
611  
612 sub findnodes
613 {
614 my( $self, $path ) = @_;
615 return( $self->xp->findnodes( $path, $self ) );
616 }
617  
618 sub findnodes_as_string
619 {
620 my( $self, $path ) = @_;
621 return( $self->xp->findnodes_as_string( $path, $self ) );
622 }
623  
624 sub findnodes_as_strings
625 {
626 my( $self, $path ) = @_;
627 return( $self->xp->findnodes_as_strings( $path, $self ) );
628 }
629  
630 sub findvalue
631 {
632 my( $self, $path ) = @_;
633 return( $self->xp->findvalue( $path, $self ) );
634 }
635  
636 sub findvalues
637 {
638 my( $self, $path ) = @_;
639 return( $self->xp->findvalues( $path, $self ) );
640 }
641  
642 # Note: Property
643 sub firstChild { return( shift->nodes->first ); }
644  
645 sub getAttributes
646 {
647 my $self = shift( @_ );
648 my $rank = 0;
649 my $a = $self->attributes_sequence->map(sub
650 {
651 return( $self->new_attribute(
652 name => $_,
653 element => $self,
654 rank => $rank++,
655 value => $self->attributes->get( $_ ),
656 ) );
657 });
658 return( wantarray() ? $a->list : $a );
659 }
660  
661 sub getChildNodes
662 {
663 my $self = shift( @_ );
664 my $nodes = $self->nodes;
665 return( wantarray() ? $nodes->list : $nodes );
666 }
667  
668 sub getElementById { return; }
669  
670 # sub getFirstChild { return; }
671 sub getFirstChild { return( shift->nodes->first ); }
672  
673 # sub getLastChild { return; }
674 sub getLastChild { return( shift->nodes->last ); }
675  
676 sub getName { return; }
677  
678 sub getNextSibling { return( shift->nextSibling ); }
679  
680 sub getParentNode { return( shift->parent ); }
681  
682 sub getPreviousSibling { return( shift->previousSibling ); }
683  
684 sub getRootNode
685 {
686 my $self = shift( @_ );
687 # The parent of root is a HTML::Object::Root
688 # that helps getting the tree to mimic a DOM tree
689 # return( $self->root->getParentNode );
690 return( $self->root );
691 }
692  
693 sub hasChildNodes { return( !shift->nodes->is_empty ); }
694  
695 sub insertAfter
696 {
697 my $self = shift( @_ );
698 my $e = shift( @_ ) || return( $self->error( "No node was provided to insert." ) );
699 return( $self->error({
700 message => "Node provided (" . overload::StrVal( $e ) . ") is not an HTML::Object::DOM::Node.",
701 class => 'HTML::Object::TypeError',
702 }) ) if( !$self->_is_a( $e => 'HTML::Object::DOM::Node' ) );
703 my $refNode = shift( @_ );
704 my $nodes = $self->nodes;
705 my $pos;
706 if( !defined( $refNode ) )
707 {
708 $pos = $nodes->size;
709 }
710 else
711 {
712 return( $self->error({
713 message => "Reference node provided (" . overload::StrVal( $refNode ) . ") is not an HTML::Object::DOM::Node.",
714 class => 'HTML::Object::TypeError',
715 }) ) if( !$self->_is_a( $refNode => 'HTML::Object::DOM::Node' ) );
716 $pos = $nodes->pos( $refNode );
717 return( $self->error({
718 message => "Reference node provided (" . overload::StrVal( $refNode ) . ") is not among the document nodes.",
719 class => 'HTML::Object::HierarchyRequestError',
720 }) ) if( !defined( $pos ) );
721 return( $self->error( "Somehow, position for the reference node returned $pos, but I expected an integer equal or above 0" ) ) if( $pos < 0 );
722 }
723 my $list = $self->new_array( $self->_is_a( $e => 'HTML::Object::DOM::DocumentFragment' ) ? $e->children : $e );
724 $nodes->splice( $pos + 1, 0, $list->list );
725 $list->foreach(sub
726 {
727 $_->detach;
728 $_->parent( $self );
729 });
730 $self->reset(1);
731 if( $self->_is_a( $e => 'HTML::Object::DOM::DocumentFragment' ) )
732 {
733 $e->children->reset;
734 }
735 return( $e );
736 }
737  
738 sub insertBefore
739 {
740 my $self = shift( @_ );
741 my $e = shift( @_ ) || return( $self->error( "No node was provided to insert." ) );
742 return( $self->error({
743 message => "Node provided (" . overload::StrVal( $e ) . ") is not an HTML::Object::DOM::Node.",
744 class => 'HTML::Object::TypeError',
745 }) ) if( !$self->_is_a( $e => 'HTML::Object::DOM::Node' ) );
746 my $refNode = shift( @_ );
747 my $nodes = $self->nodes;
748 my $pos;
749 if( !defined( $refNode ) )
750 {
751 $pos = $nodes->length; # set the position to size + 1 to make it equivalent to a push()
752 }
753 else
754 {
755 return( $self->error({
756 message => "Reference node provided (" . overload::StrVal( $refNode ) . ") is not an HTML::Object::DOM::Node.",
757 class => 'HTML::Object::TypeError',
758 }) ) if( !$self->_is_a( $refNode => 'HTML::Object::DOM::Node' ) );
759 $pos = $nodes->pos( $refNode );
760 return( $self->error({
761 message => "Reference node provided (" . overload::StrVal( $refNode ) . ") is not among the document nodes.",
762 class => 'HTML::Object::HierarchyRequestError',
763 }) ) if( !defined( $pos ) );
764 return( $self->error( "Somehow, position for the reference node returned $pos, but I expected an integer equal or above 0" ) ) if( $pos < 0 );
765 }
766 my $list = $self->new_array( $self->_is_a( $e => 'HTML::Object::DOM::DocumentFragment' ) ? $e->children : $e );
767 $nodes->splice( $pos, 0, $list->list );
768 $list->foreach(sub
769 {
770 $_->detach;
771 $_->parent( $self );
772 });
773 $self->reset(1);
774 if( $self->_is_a( $e => 'HTML::Object::DOM::DocumentFragment' ) )
775 {
776 $e->children->reset;
777 }
778 return( $e );
779 }
780  
781 sub isAttributeNode { return(0); }
782  
783 sub isCommentNode { return(0); }
784  
785 # Note: Property
786 sub isConnected
787 {
788 my $self = shift( @_ );
789 my $root = $self->root;
790 return( $self->false ) if( !$root );
791 return( $root->isa( 'HTML::Object::Document' ) ? $self->true : $self->false );
792 }
793  
794 sub isDefaultNamespace
795 {
796 my $self = shift( @_ );
797 my $uri = shift( @_ );
798 return( $self->error( "No namespace URI was provided to check." ) ) if( !defined( $uri ) );
799 if( $self->tag eq 'svg' )
800 {
801 return( $self->attributes->get( 'xmlns' ) eq $uri );
802 }
803 else
804 {
805 return( $uri eq "" );
806 }
807 }
808  
809 sub isEqualNode
810 {
811 my $self = shift( @_ );
812 my $e = shift( @_ ) || return( $self->error( "No html element was provided to check for equality." ) );
813 return( $self->error( "Element provided (", overload::StrVal( $e ), ") is not an HTML::Object::Element." ) ) if( !$self->_is_a( $e => 'HTML::Object::Element' ) );
814 return(0) if( $self->nodeType != $e->nodeType );
815 return(0) if( $self->children->length != $e->children->length );
816 return(0) if( $self->attributes_sequence->join( ',' ) ne $e->attributes_sequence->join( ',' ) );
817 my $failed = 0;
818 $self->attributes_sequence->foreach(sub
819 {
820 my $v1 = $self->attributes->get( $_ );
821 my $v2 = $e->attributes->get( $_ );
822 if( $v1 ne $v2 )
823 {
824 $failed++;
825 return(0);
826 }
827 });
828 return(0) if( $failed );
829 return(1);
830 }
831  
832 sub isElementNode { return(0); }
833  
834 sub isNamespaceNode { return(0); }
835  
836 sub isPINode { return(0); }
837  
838 sub isProcessingInstructionNode { return(0); }
839  
840 sub isSameNode
841 {
842 return(0) if( !defined( $_[1] ) );
843 if( !$_[0]->_is_a( $_[1] => 'HTML::Object::DOM::Node' ) )
844 {
845 warn( "Value provided ($_[1]) is not a reference.\n" ) if( $_[0]->_warnings_is_enabled );
846 return(0);
847 }
848 return( Scalar::Util::refaddr( $_[0] ) eq Scalar::Util::refaddr( $_[1] ) );
849 }
850  
851 sub isTextNode { return(0); }
852  
853 # Node: Property
854 sub lastChild { return( shift->nodes->last ); }
855  
856 sub lookupNamespaceURI
857 {
858 my $self = shift( @_ );
859 my $prefix = shift( @_ ) || return( '' );
860 return( XML_DEFAULT_NAMESPACE ) if( lc( $prefix ) eq 'xml' );
861 return( '' );
862 }
863  
864 sub lookupPrefix { return; }
865  
866 sub new_closing
867 {
868 my $self = shift( @_ );
869 $self->_load_class( 'HTML::Object::DOM::Closing' ) || return( $self->pass_error );
870 my $e = HTML::Object::DOM::Closing->new( @_ ) ||
871 return( $self->pass_error( HTML::Object::DOM::Closing->error ) );
872 return( $e );
873 }
874  
875 sub new_comment
876 {
877 my $self = shift( @_ );
878 $self->_load_class( 'HTML::Object::DOM::Comment' ) || return( $self->pass_error );
879 my $e = HTML::Object::DOM::Comment->new( @_ ) ||
880 return( $self->pass_error( HTML::Object::DOM::Comment->error ) );
881 return( $e );
882 }
883  
884 sub new_element
885 {
886 my $self = shift( @_ );
887 $self->_load_class( 'HTML::Object::DOM::Element' ) || return( $self->pass_error );
888 my $e = HTML::Object::DOM::Element->new( @_ ) ||
889 return( $self->pass_error( HTML::Object::DOM::Element->error ) );
890 return( $e );
891 }
892  
893 sub new_parser
894 {
895 my $self = shift( @_ );
896 $self->_load_class( 'HTML::Object::DOM' ) || return( $self->pass_error );
897 my $p = HTML::Object::DOM->new( debug => $self->debug ) ||
898 return( $self->pass_error( HTML::Object::DOM->error ) );
899 return( $p );
900 }
901  
902 sub new_text
903 {
904 my $self = shift( @_ );
905 $self->_load_class( 'HTML::Object::DOM::Text' ) || return( $self->pass_error );
906 my $e = HTML::Object::DOM::Text->new( @_ ) ||
907 return( $self->pass_error( HTML::Object::DOM::Text->error ) );
908 return( $e );
909 }
910  
911 # Note: Property
912 sub nextSibling { return( shift->right->first ); }
913  
914 # Note: Property
915 sub nodeName
916 {
917 my $self = shift( @_ );
918 my $class = ref( $self ) || $self;
919 my $map =
920 {
921 Comment => '#comment',
922 Document => '#document',
923 DocumentFragment => '#documentFragment',
924 Space => '#space',
925 Text => '#text',
926 };
927 my $type = [split( /::/, $class )]->[-1];
928 return( CORE::exists( $map->{ $type } ) ? $map->{ $type } : $self->tag );
929 }
930  
931 # For any nodes except for Document, nodes are the same as children
932 sub nodes { return( shift->children( @_ ) ); }
933  
934 # ELEMENT_NODE 1
935 # ATTRIBUTE_NODE 2
936 # TEXT_NODE 3
937 # CDATA_SECTION_NODE 4
938 # PROCESSING_INSTRUCTION_NODE 7
939 # COMMENT_NODE 8
940 # DOCUMENT_NODE 9
941 # DOCUMENT_TYPE_NODE 10
942 # DOCUMENT_FRAGMENT_NODE 11
943 # <https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType>
944 # Note: Property
945 sub nodeType
946 {
947 my $self = shift( @_ );
948 my $map =
949 [
950 # Document also inherits from Element, so we test it first
951 'HTML::Object::DOM::Document' => DOCUMENT_NODE,
952 'HTML::Object::DOM::Element' => ELEMENT_NODE,
953 'HTML::Object::DOM::Attribute' => ATTRIBUTE_NODE,
954 'HTML::Object::DOM::Text' => TEXT_NODE,
955 # Nothing for CData (4) or Processing Instruction (7)
956 'HTML::Object::DOM::Comment' => COMMENT_NODE,
957 'HTML::Object::DOM::Declaration' => DOCUMENT_TYPE_NODE,
958 'HTML::Object::DOM::DocumentFragment' => DOCUMENT_FRAGMENT_NODE,
959 # We treat space separately, but the DOM normally treats it as text
960 'HTML::Object::DOM::Space' => SPACE_NODE,
961 ];
962
963 # return( $map->{ [split( /::/, ( ref( $self ) || $self ) )]->[-1] } );
964 for( my $i = 0; $i < scalar( @$map ); $i += 2 )
965 {
966 my $class = $map->[$i];
967 my $const = $map->[$i + 1];
968 if( $self->isa( $class ) )
969 {
970 return( $const );
971 }
972 }
973 return;
974 }
975  
976 # Note: Property
977 sub nodeValue { return; }
978  
979 sub normalize
980 {
981 my $self = shift( @_ );
982 my $process;
983 $process = sub
984 {
985 my $e = shift( @_ );
986 my $new = $self->new_array;
987 my $found = '';
988 $e->children->foreach(sub
989 {
990 my $kid = shift( @_ );
991 # text
992 if( $kid->nodeType == 3 )
993 {
994 if( $found )
995 {
996 # merge it with previous text element and skip it
997 $found->value->append( $kid->value->scalar );
998 # next
999 return(1);
1000 }
1001 # We found a text element. Save it and merge it with siblings, if any
1002 else
1003 {
1004 $found = $kid;
1005 }
1006 }
1007 else
1008 {
1009 $found = '';
1010 }
1011 $new->push( $kid );
1012 });
1013 # Set the new children elements array object
1014 $e->children( $new );
1015 };
1016 $process->( $self );
1017 return( $self );
1018 }
1019  
1020 # Note: Property
1021 sub ownerDocument
1022 {
1023 my $self = shift( @_ );
1024 my $root = $self->root;
1025 return( $root );
1026 }
1027  
1028 sub parent { return( shift->_set_get_object_without_init({
1029 field => 'parent',
1030 weaken => 1,
1031 }, 'HTML::Object::DOM::Node', @_ ) ); }
1032  
1033 # Note: Property
1034 sub parentNode { return( shift->parent ); }
1035  
1036 # Note: Property
1037 # "Returns an Element that is the parent of this node. If the node has no parent, or if that parent is not an Element, this property returns null."
1038 sub parentElement
1039 {
1040 my $self = shift( @_ );
1041 my $parent = $self->parent;
1042 return( $parent ) if( defined( $parent ) && $self->_is_a( $parent => 'HTML::Object::DOM::Element' ) );
1043 return;
1044 }
1045  
1046 # Note: Property
1047 # The last element of our siblings, is our first element on our left
1048 sub previousSibling { return( shift->left->last ); }
1049  
1050 sub removeChild
1051 {
1052 my $self = shift( @_ );
1053 my $elem = shift( @_ ) || return( $self->error({
1054 message => "No element was provided to remove.",
1055 class => 'HTML::Object::TypeError'
1056 }) );
1057 return( $self->error({
1058 message => "Element provided (" . overload::StrVal( $elem ) . ") is actually not an HTML element.",
1059 class => 'HTML::Object::TypeError'
1060 }) ) if( !$self->_is_a( $elem => 'HTML::Object::Element' ) );
1061 my $nodes = $self->nodes;
1062 my $pos = $nodes->pos( $elem );
1063 return( $self->error({
1064 message => "Node to remove was not found among the current object's children.",
1065 class => 'HTML::Object::NotFoundError',
1066 }) ) if( !defined( $pos ) );
1067 $nodes->splice( $pos, 1 );
1068 $elem->parent( undef );
1069 # Remove the closing tag also, if there are any.
1070 if( my $close = $elem->close_tag )
1071 {
1072 if( defined( $pos = $nodes->pos( $close ) ) )
1073 {
1074 $nodes->splice( $pos, 1 );
1075 }
1076 }
1077 $self->reset(1);
1078 return( $elem );
1079 }
1080  
1081 sub replaceChild
1082 {
1083 my $self = shift( @_ );
1084 return( $self->error({
1085 message => sprintf( "At least 2 arguments are required, but only %d provided.", scalar( @_ ) ),
1086 class => 'HTML::Object::TypeError',
1087 }) ) if( scalar( @_ ) < 2 );
1088 my( $new, $old ) = @_;
1089 my $new_parent = $new->parent;
1090 my $old_parent = $old->parent;
1091 my $parent = $self->parent;
1092 if( !$parent )
1093 {
1094 return( $self->error({
1095 message => "Current node does not have any parent.",
1096 class => 'HTML::Object::HierarchyRequestError',
1097 }) );
1098 }
1099 elsif( !$old_parent )
1100 {
1101 return( $self->error({
1102 message => "Old node provided does not have any parent",
1103 class => 'HTML::Object::HierarchyRequestError',
1104 }) );
1105 }
1106 elsif( $old_parent ne $self )
1107 {
1108 return( $self->error({
1109 message => "Old node parent is not the current node.",
1110 class => 'HTML::Object::NotFoundError',
1111 }) );
1112 }
1113 elsif( !$self->_is_a( $old_parent => 'HTML::Object::DOM::Document' ) &&
1114 !$self->_is_a( $old_parent => 'HTML::Object::DOM::DocumentFragment' ) &&
1115 !$self->_is_a( $old_parent => 'HTML::Object::DOM::Element' ) )
1116 {
1117 return( $self->error({
1118 message => "Old node's parent is not an HTML::Object::DOM::Document, HTML::Object::DOM::DocumentFragment or HTML::Object::DOM::Element object.",
1119 class => 'HTML::Object::HierarchyRequestError',
1120 }) );
1121 }
1122 elsif( !$self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) &&
1123 !$self->_is_a( $new => 'HTML::Object::DOM::Declaration' ) &&
1124 !$self->_is_a( $new => 'HTML::Object::DOM::Element' ) &&
1125 !$self->_is_a( $new => 'HTML::Object::DOM::CharacterData' ) )
1126 {
1127 return( $self->error({
1128 message => "New node is not an HTML::Object::DOM::DocumentFragment, HTML::Object::DOM::Declaration, HTML::Object::DOM::Element or HTML::Object::DOM::CharacterData object.",
1129 class => 'HTML::Object::HierarchyRequestError',
1130 }) );
1131 }
1132 elsif( $self->lineage->has( $new ) )
1133 {
1134 return( $self->error({
1135 message => "New node provided is an ancestor of the current node.",
1136 class => 'HTML::Object::HierarchyRequestError',
1137 }) );
1138 }
1139 elsif( ( $self->_is_a( $new => 'HTML::Object::DOM::Text' ) || $self->_is_a( $new => 'HTML::Object::DOM::Space' ) ) &&
1140 $self->_is_a( $new_parent => 'HTML::Object::DOM::Document' ) )
1141 {
1142 return( $self->error({
1143 message => "New node is a HTML::Object::DOM::Text or HTML::Object::DOM::Space node and its parent is a HTML::Object::DOM::Document node.",
1144 class => 'HTML::Object::HierarchyRequestError',
1145 }) );
1146 }
1147 elsif( $self->isa( 'HTML::Object::DOM::Declaration' ) && !$self->_is_a( $parent => 'HTML::Object::DOM::Document' ) )
1148 {
1149 return( $self->error({
1150 message => "Current node is a DocumentType, but its parent is not an HTML::Object::DOM::Document object.",
1151 class => 'HTML::Object::HierarchyRequestError',
1152 }) );
1153 }
1154 elsif( $self->_is_a( $parent => 'HTML::Object::DOM::Document' ) &&
1155 $self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) &&
1156 ( $new->childElementCount > 1 || $new->children->grep(sub{ $self->_is_a( $_ => 'HTML::Object::DOM::Text' ) })->length ) )
1157 {
1158 return( $self->error({
1159 message => "Current node parent is a HTML::Object::DOM::Document object and new node is a HTML::Object::DOM::DocumentFragment object that has either more than 1 element or has a HTML::Object::DOM::Text node.",
1160 class => 'HTML::Object::HierarchyRequestError',
1161 }) );
1162 }
1163 elsif( $self->_is_a( $parent => 'HTML::Object::DOM::Document' ) &&
1164 $parent->childElementCount > 0 &&
1165 $self->_is_a( $new => 'HTML::Object::DOM::Element' ) &&
1166 # Non-standard addition:
1167 # replacement is not forbidden if the user replace an element that is not an HTML element by an HTML element and there is no HTML element yet or
1168 # the user replace an HTML element by another HTML element
1169 !(
1170 ( $self->_is_a( $old => 'HTML::Object::DOM::Element' ) &&
1171 !$self->_is_a( $old => 'HTML::Object::DOM::Element::HTML' ) &&
1172 $parent->children->grep(sub{ $self->_is_a( $_ => 'HTML::Object::DOM::Element::HTML' ) })->is_empty &&
1173 $self->_is_a( $new => 'HTML::Object::DOM::Element::HTML' ) ) ||
1174 ( $self->_is_a( $old => 'HTML::Object::DOM::Element::HTML' ) &&
1175 $self->_is_a( $new => 'HTML::Object::DOM::Element::HTML' ) )
1176 ) )
1177 {
1178 return( $self->error({
1179 message => "Attempting to replace a child element in a Document with another non HTML-tag element. Document can have only one Element: the HTML-tag element.",
1180 class => 'HTML::Object::HierarchyRequestError',
1181 }) );
1182 }
1183 elsif( $self->_is_a( $new => 'HTML::Object::DOM::Element' ) &&
1184 $self->_is_a( $old->previousSibling => 'HTML::Object::DOM::Declaration' ) )
1185 {
1186 return( $self->error({
1187 message => "Attempting to add an Element object before a DocumentType object",
1188 class => 'HTML::Object::HierarchyRequestError',
1189 }) );
1190 }
1191 # We use 'nodes' rather than 'children' so this works well with HTML::Object::DOM::Document
1192 my $nodes = $self->nodes;
1193 my $newPos = $nodes->pos( $new );
1194 my $oldPos = $nodes->pos( $old );
1195 if( defined( $newPos ) && !defined( $oldPos ) )
1196 {
1197 return( $self->error({
1198 message => "New child already has this parent and old child does not. Please check the order of replaceChild's arguments.",
1199 class => 'HTML::Object::NotFoundError',
1200 }) );
1201 }
1202 elsif( !defined( $oldPos ) )
1203 {
1204 return( $self->error({
1205 message => "Child to be replaced is not a child of this node",
1206 class => 'HTML::Object::NotFoundError',
1207 }) );
1208 }
1209 $new->detach;
1210 my $new_array = $self->new_array( $self->_is_a( $new => 'HTML::Object::DOM::DocumentFragment' ) ? $new->children : $new );
1211 $new_array->foreach(sub
1212 {
1213 return(1) if( !$self->_is_a( $_ => 'HTML::Object::DOM::Node' ) );
1214 $_->parent( $self );
1215 });
1216 $nodes->splice( $oldPos, 1, $new_array->list );
1217 $old->parent( undef );
1218 $self->reset(1);
1219 return( $old );
1220 }
1221  
1222 sub textContent : lvalue { return( shift->_set_get_callback({
1223 get => sub
1224 {
1225 my $self = shift( @_ );
1226 return if( $self->isa( 'HTML::Object::DOM::Document' ) );
1227 unless( $self->isa( 'HTML::Object::DOM::Comment' ) ||
1228 $self->isa( 'HTML::Object::DOM::Text' ) ||
1229 $self->isa( 'HTML::Object::DOM::Element' ) )
1230 {
1231 return;
1232 }
1233 my $str = $self->as_text;
1234 $str =~ s,<br[[:blank:]]*/>\n,\n,gs;
1235 $str =~ s/\&gt;/>/gs;
1236 $str =~ s/\&lt;/</gs;
1237 return( $str );
1238 },
1239 set => sub
1240 {
1241 my $self = shift( @_ );
1242 my $ctx = $_;
1243 my $arg = shift( @_ );
1244 return if( $self->isa( 'HTML::Object::DOM::Document' ) );
1245 my $dummy;
1246 if( $self->isa( 'HTML::Object::DOM::Comment' ) ||
1247 $self->isa( 'HTML::Object::DOM::Text' ) ||
1248 $self->isa( 'HTML::Object::DOM::Element' ) )
1249 {
1250 if( $self->isa( 'HTML::Object::DOM::Comment' ) ||
1251 $self->isa( 'HTML::Object::DOM::Text' ) )
1252 {
1253 $self->value( $arg );
1254 }
1255 else
1256 {
1257 my $val = "$arg";
1258 $val =~ s/</\&lt;/gs;
1259 $val =~ s/>/\&gt;/gs;
1260 $val =~ s,\n,<br />\n,gs;
1261 my $e = $self->new_text( value => $val, parent => $self );
1262 $self->children->set( $e );
1263 }
1264 $self->reset(1);
1265 $dummy = 1;
1266 return( $dummy );
1267 }
1268 return( $dummy );
1269 },
1270 }, @_ ) ); }
1271  
1272 sub trigger
1273 {
1274 my $self = shift( @_ );
1275 my $type = shift( @_ );
1276 return( $self->error({
1277 message => "No event type was provided to trigger.",
1278 class => 'HTML::Object::SyntaxError',
1279 }) ) if( !defined( $type ) || !CORE::length( "$type" ) );
1280 return( $self->error({
1281 message => "Event type provided \"$type\" contains illegal characters. Only alphanuneric, underscore (\"_\") and dash (\"-\") are allowed",
1282 class => 'HTML::Object::TypeError',
1283 }) ) if( $type !~ /^\w[\w\-]*$/ );
1284 require HTML::Object::Event;
1285 my $evt = HTML::Object::Event->new( $type, @_ ) ||
1286 return( $self->pass_error( HTML::Object::Event->error ) );
1287 return( $self->dispatchEvent( $evt ) );
1288 }
1289  
1290 sub xp
1291 {
1292 my $self = shift( @_ );
1293 unless( $XP )
1294 {
1295 $self->_load_class( 'HTML::Object::XPath' ) || return( $self->pass_error );
1296 $XP = HTML::Object::XPath->new;
1297 }
1298 # $XP->debug( $self->debug );
1299 return( $XP );
1300 }
1301  
1302 sub _list_to_nodes
1303 {
1304 my $self = shift( @_ );
1305 my $list = $self->new_array;
1306 my $p = $self->new_parser;
1307 my $prev;
1308 foreach( @_ )
1309 {
1310 if( $self->_is_a( $_ => 'HTML::Object::DOM::Node' ) )
1311 {
1312 if( $self->_is_a( $_ => 'HTML::Object::DOM::DocumentFragment' ) )
1313 {
1314 my $kids = $_->children->clone;
1315 $_->children->reset;
1316 foreach my $kid ( @$kids )
1317 {
1318 $kid->detach;
1319 }
1320 $list->push( $kids->list );
1321 }
1322 else
1323 {
1324 $list->push( $_ );
1325 $_->detach;
1326 }
1327 undef( $prev );
1328 }
1329 # HTML string
1330 elsif( !ref( $_ ) || ( ref( $_ ) && overload::Method( $_, '""' ) ) )
1331 {
1332 if( $self->looks_like_html( $_ ) )
1333 {
1334 my $doc = $p->parse_data( $_ ) ||
1335 return( $self->pass_error({ class => 'HTML::Object::TypeError' }) );
1336 $list->push( $doc->children->list ) if( !$doc->children->is_empty );
1337 undef( $prev );
1338 }
1339 else
1340 {
1341 if( defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::DOM::Text' ) )
1342 {
1343 $prev->value->append( $_ );
1344 }
1345 else
1346 {
1347 my $e = $self->new_text( value => $_ );
1348 $list->push( $e );
1349 $prev = $e;
1350 }
1351 }
1352 }
1353 else
1354 {
1355 return( $self->error({
1356 message => "Unsupported data provided (" . overload::StrVal( $_ ) . ").",
1357 class => 'HTML::Object::TypeError',
1358 }) );
1359 }
1360 }
1361 return( $list );
1362 }
1363  
1364 sub _xpath_value
1365 {
1366 my $self = shift( @_ );
1367 my $this = shift( @_ );
1368 my $opts = $self->_get_args_as_hash( @_ );
1369 if( ref( $this ) )
1370 {
1371 return( $$this );
1372 }
1373 else
1374 {
1375 $self->_load_class( 'HTML::Selector::XPath' ) ||
1376 return( $self->pass_error );
1377 # try-catch
1378 local $@;
1379 my $rv = eval
1380 {
1381 return( HTML::Selector::XPath::selector_to_xpath( $this, %$opts ) );
1382 };
1383 if( $@ )
1384 {
1385 return( $self->error( "Bad selector \"$this\": $@" ) );
1386 }
1387 return( $rv );
1388 }
1389 }
1390  
1391 1;
1392 # NOTE: POD
1393 __END__
1394  
1395 =encoding utf-8
1396  
1397 =head1 NAME
1398  
1399 HTML::Object::DOM::Node - HTML Object DOM Node Class
1400  
1401 =head1 SYNOPSIS
1402  
1403 use HTML::Object::DOM::Node;
1404 my $node = HTML::Object::DOM::Node->new ||
1405 die( HTML::Object::DOM::Node->error, "\n" );
1406  
1407 =head1 VERSION
1408  
1409 v0.3.0_1
1410  
1411 =head1 DESCRIPTION
1412  
1413 This module implement the properties and methods for HTML DOM nodes. It inherits from L<HTML::Object::EventTarget> and is used by L<HTML::Object::DOM::Element>
1414  
1415 =head1 INHERITANCE
1416  
1417 +-----------------------+ +---------------------------+ +-------------------------+
1418 | HTML::Object::Element | --> | HTML::Object::EventTarget | --> | HTML::Object::DOM::Node |
1419 +-----------------------+ +---------------------------+ +-------------------------+
1420  
1421 =head1 PROPERTIES
1422  
1423 All the following properties can be used as lvalue method as well as regular method. For example with L</baseURI>
1424  
1425 # Get the base uri, if any
1426 my $uri = $e->baseURI;
1427 $e->baseURI = 'https://example.org/some/where';
1428 # or
1429 $e->baseURI( 'https://example.org/some/where' );
1430  
1431 =head2 baseURI
1432  
1433 Normally this is read-only, but in this api, you can set an URI.
1434  
1435 This returns an L<URI> object representing the base URL of the document containing the Node, if any.
1436  
1437 The base URL is determined as follows:
1438  
1439 =over 4
1440  
1441 =item 1. By default, the base URL is the location of the document (as set by L<HTML::Object/parse_url>).
1442  
1443 =item 2. If it is an L<HTML Document|HTML::Object::DOM::Document> and there is a L<<base>|https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base> element in the L<document|HTML::Object::DOM::Document>, the hrefvalue of the first Base element with such an attribute is used instead.
1444  
1445 =item 3. By specifying an uri with L<HTML::Object::DOM::Document/documentURI> or L<HTML::Object::DOM::Document/URL>
1446  
1447 =back
1448  
1449 =head2 childNodes
1450  
1451 Read-only
1452  
1453 This returns an L<array object|Module::Generic::Array> 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 L<list object|Module::Generic::Array> is automatically updated.
1454  
1455 =head2 firstChild
1456  
1457 Read-only
1458  
1459 This returns an element representing the first direct child element of the element, or C<undef> if the element has no child.
1460  
1461 =head2 isConnected
1462  
1463 Returns a boolean indicating whether or not the element is connected (directly or indirectly) to the context object, i.e. the L<Document object|HTML::Object::Document> in the case of the normal DOM.
1464  
1465 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected>
1466  
1467 =head2 lastChild
1468  
1469 Read-only
1470  
1471 This returns an element representing the last direct child element of the element, or C<undef> if the element has no child.
1472  
1473 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/lastChild>
1474  
1475 =head2 nextSibling
1476  
1477 Read-only
1478  
1479 This returns an element representing the next element in the tree, or C<undef> if there is not such element.
1480  
1481 The next node could also be a L<whitespace|HTML::Object::DOM::Space> or a L<text|HTML::Object::DOM::Text>. If you want to get the next element and not just any node, use L<nextElementSibling|HTML::Object::DOM/nextElementSibling> instead.
1482  
1483 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling>
1484  
1485 =head2 nodeName
1486  
1487 Read-only
1488  
1489 This returns a string containing the name of the element. The structure of the name will differ with the element type. E.g. An L<HTML Element|HTML::Object::Element> will contain the name of the corresponding tag, like 'audio' for an HTML audio element, a L<Text|HTML::Object::Text> element will have the '#text' string, or a L<Document|HTML::Object::Document> element will have the '#document' string.
1490  
1491 For L<HTML element|HTML::Object::DOM::Element>, contrary to the standard specifications, is not the uppercase value of the tag name, but the lowercase value. However, if you really wanted the uppercase value, you could get it quite easily like so:
1492  
1493 $e->nodeName->uc;
1494  
1495 This is because L<HTML::Object::Element/tag> returns a L<scalar object|Module::Generic::Scalar>
1496  
1497 Example:
1498  
1499 This is some html:
1500 <div id="d1">Hello world</div>
1501 <!-- Example of comment -->
1502 Text <span>Text</span>
1503 Text<br/>
1504 <svg height="20" width="20">
1505 <circle cx="10" cy="10" r="5" stroke="black" stroke-width="1" fill="red" />
1506 <hr>
1507 <output id="result">Not calculated yet.</output>
1508  
1509 then, with the script:
1510  
1511 let node = document.getElementsByTagName("body")[0].firstChild;
1512 let result = "Node names are:<br/>";
1513 while (node) {
1514 result += node.nodeName + "<br/>";
1515 node = node.nextSibling
1516 }
1517  
1518 const output = document.getElementById("result");
1519 output.innerHTML = result;
1520  
1521 would produce:
1522  
1523 Node names are:
1524 #text
1525 div
1526 #text
1527 #comment
1528 #text
1529 span
1530 #text
1531 br
1532 #text
1533 svg
1534 hr
1535 #text
1536 output
1537 #text
1538 script
1539  
1540 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName>
1541  
1542 =head2 nodeType
1543  
1544 Read-only
1545  
1546 This returns an integer representing the type of the element. Possible values are:
1547  
1548 =over 4
1549  
1550 =item 1. element node
1551  
1552 =item 2. attribute node
1553  
1554 =item 3. text node
1555  
1556 =item 4. CDATA section node
1557  
1558 =item 5. unused (formerly entity reference node)
1559  
1560 =item 6. unused (formerly entity node)
1561  
1562 =item 7. processing instruction node
1563  
1564 =item 8. comment node
1565  
1566 =item 9. document node
1567  
1568 =item 10. document type node
1569  
1570 =item 11. document fragment node
1571  
1572 =item 12. notation node
1573  
1574 =item 13. space node
1575  
1576 =back
1577  
1578 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType>
1579  
1580 =head2 nodeValue
1581  
1582 This returns or sets the value of the current node.
1583  
1584 For document, element or collection, this returns C<undef> and for attribute, text or comment, this sets or returns the objct value.
1585  
1586 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue>
1587  
1588 =head2 ownerDocument
1589  
1590 Read-only
1591  
1592 This returns the L<Document|HTML::Object::Document> that this element belongs to. If the element is itself a document, returns C<undef>.
1593  
1594 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument>
1595  
1596 =head2 parentNode
1597  
1598 Read-only
1599  
1600 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 C<undef>.
1601  
1602 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode>
1603  
1604 =head2 parentElement
1605  
1606 Read-only
1607  
1608 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 C<undef>.
1609  
1610 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement>
1611  
1612 =head2 previousSibling
1613  
1614 Read-only
1615  
1616 This returns a element representing the previous element in the tree, or C<undef> if there is not such element.
1617  
1618 The previous node could also be a L<whitespace|HTML::Object::DOM::Space> or a L<text|HTML::Object::DOM::Text>. If you want to get the previous element and not just any node, use L<previousElementSibling|HTML::Object::DOM/previousElementSibling> instead.
1619  
1620 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling>
1621  
1622 =head2 textContent
1623  
1624 Returns / Sets the textual content of an element and all its descendants.
1625  
1626 If this is called on a L<text node|HTML::Object::DOM::Text> or a L<comment node|HTML::Object::DOM::Comment>, it will, instead, set the object value to the textual content provided.
1627  
1628 When setting some values, this method will ensure that HTML characters are escaped, namely: C<< < >>, C<< > >> and new lines are preceded by the C<< <br /> >> tag.
1629  
1630 When the value is retrieved, this is reversed.
1631  
1632 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent>
1633  
1634 See also L<HTML::Object::DOM::Element/innerText>, L<HTML::Object::Element/as_text> and L<HTML::Object::XQuery/text>
1635  
1636 =head1 METHODS
1637  
1638 =head2 addEventListener
1639  
1640 Registers an event handler to a specific event type on the node. This is inherited from L<HTML::Object::EventTarget>
1641  
1642 See L<HTML::Object::EventTarget/addEventListener> for more information.
1643  
1644 =head2 appendChild
1645  
1646 Adds the specified C<child> L<element|HTML::Object::Element> argument as the last child to the current L<element|HTML::Object::Element>. If the argument referenced an existing L<element|HTML::Object::Element> on the DOM tree, the element will be detached from its current position and attached at the new position.
1647  
1648 If the given C<child> is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, the entire contents of the L<DocumentFragment|HTML::Object::DOM::DocumentFragment> are moved into the child list of the specified parent node.
1649  
1650 It returns the element added, except when the C<child> is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, in which case the empty L<DocumentFragment|HTML::Object::DOM::DocumentFragment> is returned.
1651  
1652 It returns C<undef> and sets an C<HTML::Object::HierarchyRequestError> error
1653  
1654 =over 4
1655  
1656 =item * the parent of C<child> is not a L<Document|HTML::Object::DOM::Document>, L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, or an L<Element|HTML::Object::DOM::Element>.
1657  
1658 =item * the insertion of C<child> would lead to a cycle, that is If C<child> is an ancestor of the node.
1659  
1660 =item * C<child> is not a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, a L<DocumentType|HTML::Object::DOM::Declaration>, an L<Element|HTML::Object::DOM::Element>, or a L<CharacterData|HTML::Object::DOM::CharacterData>.
1661  
1662 =item * the current node is a L<Text|HTML::Object::DOM::Text>, and its parent is a L<Document|HTML::Object::DOM::Document>.
1663  
1664 =item * the current node is a L<DocumentType|HTML::Object::DOM::Declaration> and its parent is not a L<Document|HTML::Object::DOM::Document>, as a doctype should always be a direct descendant of a document.
1665  
1666 =item * the parent of the node is a L<Document|HTML::Object::DOM::Document> and C<child> is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment> with more than one L<Element|HTML::Object::DOM::Element> child, or that has a L<Text|HTML::Object::DOM::Text> child.
1667  
1668 =item * the insertion of C<child> would lead to L<Document|HTML::Object::DOM::Document> with more than one L<Element|HTML::Object::DOM::Element> as child.
1669  
1670 =item * the insertion of C<child> would lead to the presence of an L<Element|HTML::Object::DOM::Element> node before a L<DocumentType|HTML::Object::DOM::Declaration> node.
1671  
1672 =back
1673  
1674 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild>
1675  
1676 =head2 appendNodes
1677  
1678 Provided with some nodes, and this will add them to the list of nodes for the current node.
1679  
1680 Returns the current node object.
1681  
1682 =head2 cloneNode
1683  
1684 Clone an element, and optionally, all of its contents. By default, it clones the content of the element.
1685  
1686 To clone a node to insert into a different document, use L<HTML::Object::DOM::Document/importNode> instead.
1687  
1688 Returns the element cloned. The cloned node has no parent and is not part of the document, until it is added to another node that is part of the document, using L</appendChild> or a similar method.
1689  
1690 See also L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode>
1691  
1692 =head2 compareDocumentPosition
1693  
1694 Compares the position of the current element against another element in any other document and returns a bitwise value comprised of one or more of the following constants (that are automatically exported):
1695  
1696 =over 4
1697  
1698 =item * DOCUMENT_POSITION_IDENTICAL (0 or in bits: 000000)
1699  
1700 Elements are identical.
1701  
1702 =item * DOCUMENT_POSITION_DISCONNECTED (1 or in bits: 000001)
1703  
1704 No relationship, both nodes are in different documents or different trees in the same document.
1705  
1706 =item * DOCUMENT_POSITION_PRECEDING (2 or in bits: 000010)
1707  
1708 The specified node precedes the current node.
1709  
1710 =item * DOCUMENT_POSITION_FOLLOWING (4 or in bits: 000100)
1711  
1712 The specified node follows the current node.
1713  
1714 =item * DOCUMENT_POSITION_CONTAINS (8 or in bits: 001000)
1715  
1716 The otherNode is an ancestor of / contains the current node.
1717  
1718 =item * DOCUMENT_POSITION_CONTAINED_BY (16 or in bits: 010000)
1719  
1720 The otherNode is a descendant of / contained by the node.
1721  
1722 =item * DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC (32 or in bits: 100000)
1723  
1724 The specified node and the current node have no common container node or the two nodes are different attributes of the same node.
1725  
1726 =back
1727  
1728 use HTML::Object::DOM::Node;
1729 my $head = $doc->head;
1730 my $body = $doc->body;
1731  
1732 if( $head->compareDocumentPosition( $body ) & DOCUMENT_POSITION_FOLLOWING )
1733 {
1734 say( 'Well-formed document' );
1735 }
1736 else
1737 {
1738 say( '<head> is not before <body>' );
1739 }
1740  
1741 For example:
1742  
1743 <div id="writeroot">
1744 <form>
1745 <input id="test" />
1746 </form>
1747 </div>
1748  
1749 my $x = $doc->getElementById('writeroot');
1750 my $y = $doc->getElementById('test');
1751 say( $x->compareDocumentPosition( $y ) ); # 20, i.e. 16 | 4
1752 say( $y->compareDocumentPosition( $x ) ); # 10, i.e. 8 | 2
1753  
1754 Be careful that, since this method does quite a bit of searching among various hierarchies, this method is a bit expensive, especially on large documents.
1755  
1756 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition> and also this L<blog post from John Resig|https://johnresig.com/blog/comparing-document-position/> or L<this one from Peter-Paul Koch|https://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html>
1757  
1758 Also the L<W3C specifications|http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-compareDocumentPosition> and L<here|http://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition>
1759  
1760 =head2 contains
1761  
1762 Returns true or false value indicating whether or not an element is a descendant of the calling element.
1763  
1764 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/contains>
1765  
1766 =head2 dispatchEvent
1767  
1768 Dispatches an event to this node in the DOM and returns a boolean value that indicates whether no handler canceled the event. This is inherited from L<HTML::Object::EventTarget>
1769
1770 See L<HTML::Object::EventTarget/dispatchEvent> for more information.
1771  
1772 =head2 find
1773  
1774 This is an alias for L</findNode>
1775  
1776 =head2 find_xpath
1777  
1778 Provided with an XPath expression and this will perform a search using the current node as the context.
1779  
1780 =head2 findNode
1781  
1782 Provided with an node object or a selector and this will search throughout the current node hierarchy using the XPath expression provided.
1783  
1784 It returns an L<array object|Module::Generic::Array> of the nodes found.
1785  
1786 =head2 findnodes
1787  
1788 Provided with an XPath expression and this will perform a search using the current node as the context.
1789  
1790 =head2 findnodes_as_string
1791  
1792 Provided with an XPath expression and this will perform a search using the current node as the context and return the result as string.
1793  
1794 =head2 findnodes_as_strings
1795  
1796 Provided with an XPath expression and this will perform a search using the current node as the context and return the result as a list of strings.
1797  
1798 =head2 findvalue
1799  
1800 Provided with an XPath expression and this will perform a search using the current node as the context and return the result as the node value.
1801  
1802 =head2 findvalues
1803  
1804 Provided with an XPath expression and this will perform a search using the current node as the context and return the result as a list of node values.
1805  
1806 =head2 getAttributes
1807  
1808 Returns a list of attribute objects for this node in list context or an L<array object|Module::Generic::Array> in scalar context.
1809  
1810 =head2 getChildNodes
1811  
1812 Returns a list of the current child nodes in list context or an L<array object|Module::Generic::Array> in scalar context.
1813  
1814 =head2 getElementById
1815  
1816 Returns an empty list in list context and an empty array reference in scalar context.
1817  
1818 =head2 getFirstChild
1819  
1820 Returns the first child node of this node, if any, or C<undef> if there are none.
1821  
1822 =head2 getLastChild
1823  
1824 Returns the last child node of this node, if any, or C<undef> if there are none.
1825  
1826 =head2 getName
1827  
1828 Returns an C<undef> and this method is superseded in L<HTML::Object::DOM::Element>
1829  
1830 =head2 getNextSibling
1831  
1832 This non-standard method is an alias for the property L</nextSibling>
1833  
1834 =head2 getParentNode
1835  
1836 Returns the current node's parent node, if any.
1837  
1838 =head2 getPreviousSibling
1839  
1840 This non-standard method is an alias for the property L</previousSibling>
1841  
1842 =head2 getRootNode
1843  
1844 Returns the context object's root.
1845  
1846 Under JavaScript, this optionally includes the shadow root if it is available. However a shadow root has no meaning under this perl interface.
1847  
1848 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode>
1849  
1850 =head2 hasChildNodes
1851  
1852 Returns a boolean value indicating whether or not the element has any child elements.
1853  
1854 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/hasChildNodes>
1855  
1856 =head2 insertAfter
1857  
1858 This is a non-standard method since it does not exist in the web API, surprisingly enough.
1859  
1860 This is exactly the same as L</insertBefore> below except it inserts the C<node> after.
1861  
1862 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/insertAfter>
1863  
1864 =head2 insertBefore
1865  
1866 Provided with a C<new> node and an optional C<reference> node and this inserts an element before the reference element as a child of a specified parent element. If the C<reference> node is C<undef>, then C<new> node is inserted at the end of current node's child nodes.
1867  
1868 If the given node already exists in the document, C<insertBefore> moves it from its current position to the new position. This means it will automatically be removed from its existing parent before appending it to the specified new parent.
1869  
1870 This means that a node cannot be in two locations of the document simultaneously.
1871  
1872 If the given child is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, the entire contents of the L<DocumentFragment|HTML::Object::DOM::DocumentFragment> are moved into the child list of the specified parent node.
1873  
1874 Returns the added child (unless C<new> is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, in which case the empty L<DocumentFragment|HTML::Object::DOM::DocumentFragment> is returned).
1875  
1876 Example:
1877  
1878 <div id="parentElement">
1879 <span id="childElement">foo bar</span>
1880 </div>
1881  
1882 # Create a new, plain <span> element
1883 my $sp1 = $doc->createElement( 'span' );
1884  
1885 # Get the reference element
1886 my $sp2 = $doc->getElementById( 'childElement' );
1887 # Get the parent element
1888 my $parentDiv = $sp2->parentNode
1889  
1890 # Insert the new element into before sp2
1891 $parentDiv->insertBefore( $sp1, $sp2 );
1892  
1893 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore>
1894  
1895 =head2 isAttributeNode
1896  
1897 Returns false by default.
1898  
1899 =head2 isCommentNode
1900  
1901 Returns false by default.
1902  
1903 =head2 isDefaultNamespace
1904  
1905 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.
1906  
1907 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/isDefaultNamespace>
1908  
1909 =head2 isElementNode
1910  
1911 Returns false by default.
1912  
1913 =head2 isEqualNode
1914  
1915 Returns a boolean value which indicates whether or not two elements are of the same type and all their defining data points match.
1916  
1917 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.
1918  
1919 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/isEqualNode>
1920  
1921 =head2 isNamespaceNode
1922  
1923 Returns false by default.
1924  
1925 =head2 isPINode
1926  
1927 Returns false by default.
1928  
1929 =head2 isProcessingInstructionNode
1930  
1931 Returns false by default.
1932  
1933 =head2 isSameNode
1934  
1935 Returns a boolean value indicating whether or not the two elements are the same (that is, they reference the same object).
1936  
1937 Example:
1938  
1939 my $div1 = $doc->createElement('div');
1940 $div1->appendChild( $doc->createTextNode('This is an element.') );
1941 my $div2 = $div1->cloneNode;
1942 say $div1->isSameNode( $div2 ); # false
1943 say $div1->isSameNode( $div1 ); # true
1944  
1945 We can also use with the equality operator:
1946  
1947 say $div1 == $div2; # false
1948 say $div1 eq $div2; # same; false
1949 say $div1 == $div1; # true
1950  
1951 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/isSameNode>
1952  
1953 =head2 isTextNode
1954  
1955 Returns false by default.
1956  
1957 =head2 lookupNamespaceURI
1958  
1959 Accepts a prefix and returns the namespace URI associated with it on the given element if found (and C<undef> if not). Supplying C<undef> for the prefix will return the default namespace.
1960  
1961 This always return an empty string and C<http://www.w3.org/XML/1998/namespace> if the prefix is C<xml>
1962  
1963 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupNamespaceURI>
1964  
1965 =head2 lookupPrefix
1966  
1967 This always returns C<undef>, because this is for XML, which is not supported.
1968  
1969 Returns a string containing the prefix for a given namespace URI, if present, and C<undef> if not.
1970  
1971 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/lookupPrefix>
1972  
1973 =head2 new_closing
1974  
1975 Returns a new L<HTML::Object::DOM::Closing> object, passing it whatever arguments were provided and return the newly instantiated object.
1976  
1977 If an error occurred, this returns C<undef> and sets an L<error|Module::Generic/error>
1978  
1979 =head2 new_comment
1980  
1981 Returns a new L<HTML::Object::DOM::Comment> object, passing it whatever arguments were provided and return the newly instantiated object.
1982  
1983 If an error occurred, this returns C<undef> and sets an L<error|Module::Generic/error>
1984  
1985 =head2 new_element
1986  
1987 Returns a new L<HTML::Object::DOM::Element> object, passing it whatever arguments were provided and return the newly instantiated object.
1988  
1989 If an error occurred, this returns C<undef> and sets an L<error|Module::Generic/error>
1990  
1991 =head2 new_parser
1992  
1993 Returns a new L<HTML::Object::DOM> object, passing it whatever arguments were provided and return the newly instantiated object.
1994  
1995 If an error occurred, this returns C<undef> and sets an L<error|Module::Generic/error>
1996  
1997 =head2 new_text
1998  
1999 Returns a new L<HTML::Object::DOM::Text> object, passing it whatever arguments were provided and return the newly instantiated object.
2000  
2001 If an error occurred, this returns C<undef> and sets an L<error|Module::Generic/error>
2002  
2003 =head2 nodes
2004  
2005 Returns the L<array object|Module::Generic::Array> containing the current node's sub nodes.
2006  
2007 =head2 normalize
2008  
2009 Clean up all the text elements under this element (merge adjacent, remove empty).
2010  
2011 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/normalize>
2012  
2013 =head2 removeChild
2014  
2015 Provided with a child node and this removes the child node from the current element, which must be a child of the current element and returns the removed node.
2016  
2017 A C<HTML::Object::NotFoundError> error is returned if the child is not a child of the node.
2018  
2019 Example:
2020  
2021 <div id="top">
2022 <div id="nested"></div>
2023 </div>
2024  
2025 To remove a specified element when knowing its parent node:
2026  
2027 my $d = $doc->getElementById('top');
2028 my $d_nested = $doc->getElementById('nested');
2029 my $throwawayNode = $d->removeChild( $d_nested );
2030  
2031 To remove a specified element without having to specify its parent node:
2032  
2033 my $node = $doc->getElementById('nested');
2034 if( $node->parentNode )
2035 {
2036 $node->parentNode->removeChild( $node );
2037 }
2038  
2039 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild>
2040  
2041 =head2 removeEventListener
2042  
2043 Removes an event listener from the node. This is inherited from L<HTML::Object::EventTarget>
2044
2045 See L<HTML::Object::EventTarget/removeEventListener> for more information.
2046  
2047 =head2 replaceChild
2048  
2049 Provided with a C<new> node and and an C<old> node and this will replace the C<old> one by the C<new> one. Note that if the C<new> node is already present somewhere else in the C<DOM>, it is first removed from that position.
2050  
2051 This returns the C<old> node removed.
2052  
2053 For L<nodes|HTML::Object::DOM::Node> that are L<elements|HTML::Object::DOM::Element>, it might be easier to read and use L<HTML::Object::DOM::Element/replaceWith>
2054  
2055 It returns C<undef> and sets an L<HTML::Object::HierarchyRequestError|Module::Generic/error> if:
2056  
2057 =over 4
2058  
2059 =item * the parent of C<old> node is not a L<Document|HTML::Object::DOM::Document>, L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, or an L<Element|HTML::Object::DOM::Element>.
2060  
2061 =item * the replacement of C<old> node by C<new> node would lead to a cycle, that is if C<new> node is an ancestor of the node.
2062  
2063 =item * C<new> is not a L<DocumentFragment|HTML::Object::DOM::DocumentFragment>, a L<DocumentType|HTML::Object::DOM::Declaration>, an L<Element|HTML::Object::DOM::Element>, or a L<CharacterData|HTML::Object::DOM::CharacterData>.
2064  
2065 =item * the current node is a L<Text|HTML::Object::DOM::Text>, and its parent is a L<Document|HTML::Object::DOM::Document>.
2066  
2067 =item * the current node is a L<DocumentType|HTML::Object::DOM::Declaration> and its parent is not a L<Document|HTML::Object::DOM::Document>, as a doctype should always be a direct descendant of a document.
2068  
2069 =item * the parent of the node is a L<Document|HTML::Object::DOM::Document> and C<new> node is a L<DocumentFragment|HTML::Object::DOM::DocumentFragment> with more than one L<Element|HTML::Object::DOM::Element> child, or that has a L<Text|HTML::Object::DOM::Text> child.
2070  
2071 =item * the replacement of C<old> node by C<new> node would lead to L<Document|HTML::Object::DOM::Document> with more than one L<Element|HTML::Object::DOM::Element> as child.
2072  
2073 =item * the replacement of C<old> node by C<new> node would lead to the presence of an L<Element|HTML::Object::DOM::Element> node before a L<DocumentType|HTML::Object::DOM::Declaration> node.
2074  
2075 =back
2076  
2077 It returns an L<HTML::Object::NotFoundError|Module::Generic/error> if the parent of C<old> is not the current node.
2078  
2079 Example:
2080  
2081 <div>
2082 <span id="childSpan">foo bar</span>
2083 </div>
2084  
2085 // Build a reference to the existing node to be replaced
2086 let sp1 = document.getElementById('childSpan');
2087 let parentDiv = sp2.parentNode;
2088 // Create an empty element node without an ID, any attributes, or any content
2089 let sp2 = document.createElement('span');
2090 // Give it an id attribute called 'newSpan'
2091 sp2.id = "newSpan";
2092 // Create some content for the new element.
2093 sp2.appendChild( document.createTextNode('new replacement span element.') );
2094 // Replace existing node sp1 with the new span element sp2
2095 parentDiv.replaceChild(sp2, sp1);
2096  
2097 Result:
2098  
2099 <div>
2100 <span id="newSpan">new replacement span element.</span>
2101 </div>
2102  
2103 See also L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild>
2104  
2105 =head2 trigger
2106  
2107 Provided with an even C<type> and this will instantiate a new L<HTML::Object::Event> object, passing it the C<type> argument, and any other arguments provided. it returns the value returned by L<HTML::Object::EventTarget/dispatchEvent>
2108  
2109 If no event type is provided, it returns a C<HTML::Object::SyntaxError> error.
2110  
2111 If the event type contains illegal characters, it returns a C<HTML::Object::TypeError> error. Accepted characters are alpha-numeric, underscore, and dash ("-").
2112  
2113 =head2 xp
2114  
2115 Returns a L<HTML::Object::XPath> object.
2116  
2117 =head1 CONSTANTS
2118  
2119 =over 4
2120  
2121 =item * DOCUMENT_POSITION_IDENTICAL (0 or in bits: 000000)
2122  
2123 Elements are identical.
2124  
2125 =item * DOCUMENT_POSITION_DISCONNECTED (1 or in bits: 000001)
2126  
2127 No relationship, both nodes are in different documents or different trees in the same document.
2128  
2129 =item * DOCUMENT_POSITION_PRECEDING (2 or in bits: 000010)
2130  
2131 The specified node precedes the current node.
2132  
2133 =item * DOCUMENT_POSITION_FOLLOWING (4 or in bits: 000100)
2134  
2135 The specified node follows the current node.
2136  
2137 =item * DOCUMENT_POSITION_CONTAINS (8 or in bits: 001000)
2138  
2139 The otherNode is an ancestor of / contains the current node.
2140  
2141 =item * DOCUMENT_POSITION_CONTAINED_BY (16 or in bits: 010000)
2142  
2143 The otherNode is a descendant of / contained by the node.
2144  
2145 =item * DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC (32 or in bits: 100000)
2146  
2147 The specified node and the current node have no common container node or the two nodes are different attributes of the same node.
2148  
2149 =back
2150  
2151 And also the following constants:
2152  
2153 =over 4
2154  
2155 =item * ELEMENT_NODE (1)
2156  
2157 =item * ATTRIBUTE_NODE (2)
2158  
2159 =item * TEXT_NODE (3)
2160  
2161 =item * CDATA_SECTION_NODE (4)
2162  
2163 =item * ENTITY_REFERENCE_NODE (5)
2164  
2165 =item * ENTITY_NODE (6)
2166  
2167 =item * PROCESSING_INSTRUCTION_NODE (7)
2168  
2169 =item * COMMENT_NODE (8)
2170  
2171 =item * DOCUMENT_NODE (9)
2172  
2173 =item * DOCUMENT_TYPE_NODE (10)
2174  
2175 =item * DOCUMENT_FRAGMENT_NODE (11)
2176  
2177 =item * NOTATION_NODE (12)
2178  
2179 =item * SPACE_NODE (13)
2180  
2181 =back
2182  
2183 =head1 AUTHOR
2184  
2185 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
2186  
2187 =head1 SEE ALSO
2188  
2189 See L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/API/Node>
2190  
2191 =head1 COPYRIGHT & LICENSE
2192  
2193 Copyright(c) 2021 DEGUEST Pte. Ltd.
2194  
2195 All rights reserved
2196  
2197 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2198  
2199 =cut