blib/lib/HTML/Object/Element.pm untested

filter: Statementstmt 0.0% 0 / 892 Branchbran 0.0% 0 / 376 Conditioncond 0.0% 0 / 274 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 109 Podpod 0.0% 0 / 95 totaltotal 0.0% 0 / 1746 CC 189 SCAR 47.1
CC
189
Cov
0%
look
600.0
as_string
380.0
new_from_lol
240.0
CRAP 111.6
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/Element.pm
3 ## Version v0.3.0_1
4 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/04/25
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::Element;
15 BEGIN
16 {
17 # For smart match
18 use v5.10.1;
19 use strict;
20 use warnings;
21 warnings::register_categories( 'HTML::Object' );
22 use parent qw( Module::Generic );
23 use vars qw( $LOOK_LIKE_HTML $LOOK_LIKE_IT_HAS_HTML $ATTRIBUTE_NAME_RE $VERSION );
24 use Data::UUID;
25 use Digest::MD5 ();
26 use Encode ();
27 use Scalar::Util ();
28 use Wanted;
29 use overload (
30 'eq' => \&_same_as,
31 '==' => \&_same_as,
32 fallback => 1,
33 );
34 our $LOOK_LIKE_HTML = qr/^[[:blank:]\h]*\<\w+.*?\>/;
35 our $LOOK_LIKE_IT_HAS_HTML = qr/\<\w+.*?\>/;
36 our $ATTRIBUTE_NAME_RE = qr/\w[\w\-]*/;
37 our $VERSION = 'v0.3.0_1';
38 };
39  
40 use strict;
41 use warnings;
42  
43 sub init
44 {
45 my $self = shift( @_ );
46 my $opts = $self->_get_args_as_hash( @_ );
47 for( qw( attributes attributes_sequence ) )
48 {
49 delete( $opts->{ $_ } ) if( !defined( $opts->{ $_ } ) );
50 }
51 my $parent = delete( $opts->{parent} );
52 $opts->{parent} = $parent;
53 $self->{attr} = {} unless( exists( $self->{attr} ) );
54 $self->{attr_seq} = [] unless( exists( $self->{attr_seq} ) );
55 $self->{checksum} = '';
56 $self->{close_tag} = '' unless( exists( $self->{close_tag} ) );
57 $self->{column} = 0;
58 # Was there a closing tag for non-void tags?
59 $self->{is_closed} = 0 unless( exists( $self->{is_closed} ) );
60 $self->{is_empty} = 0 unless( exists( $self->{is_empty} ) );
61 $self->{line} = 0;
62 $self->{modified} = 0;
63 $self->{offset} = 0;
64 $self->{original} = undef;
65 $self->{parent} = undef;
66 $self->{rank} = undef;
67 $self->{tag} = '' unless( exists( $self->{tag} ) );
68 $self->{_init_strict_use_sub} = 1;
69 $self->{_exception_class} = 'HTML::Object::Exception';
70 $self->SUPER::init( $opts ) || return( $self->pass_error );
71 $self->{children} = [];
72 # uuid
73 $self->{eid} = $self->_generate_uuid();
74 # The user is always right, so we check if the tag has a forward slash as attribute
75 # If there is one, this means this tag is an empty (void) tag.
76 # We issue a warning if our dictionary-derived value 'is_empty' says different
77 $opts->{is_empty} = 0 if( !exists( $opts->{is_empty} ) );
78 $opts->{attributes} = {} if( !exists( $opts->{attributes} ) );
79 my $attr = $opts->{attributes};
80 if( !$opts->{is_empty} && exists( $attr->{'/'} ) )
81 {
82 warn( "Tag initiated \"$opts->{tag}\" is marked as non-empty (non-void), but ends with \"/>\" at line $opts->{line} and column $opts->{column}: $opts->{original}\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
83 $self->is_empty(1);
84 }
85 $self->checksum( $self->set_checksum );
86 $self->{_cache_value} = '';
87 $self->{_internal} = {};
88 return( $self );
89 }
90  
91 # Note: HTML::Element compatibility
92 sub address
93 {
94 my $self = shift( @_ );
95 if( @_ )
96 {
97 my $addr = shift( @_ );
98 my $path = $self->new_array( [split( /\./, $addr )] );
99 my $root;
100 # relative path, such as .2.5.3
101 if( !length( $path->[0] ) )
102 {
103 $root = $self;
104 }
105 else
106 {
107 $root = $self->root;
108 return( $self->error( "First offset position should be 0 for root or a relative path." ) ) if( $path->shift != 0 );
109 }
110 my $offset;
111 while( $path->length && ( $offset = $path->shift ) )
112 {
113 return( $self->error( "Invalid offset '$offset' in path '$addr'. Value is bigger than the actual size of elements (", $root->children->size, "); starting from 0." ) ) if( $offset > $root->children->size );
114 $root = $root->children->get( $offset );
115 }
116 return( $root );
117 }
118 else
119 {
120 my $line = $self->new_array;
121 my $pos = $self->pos || 0;
122 $line->push( $pos );
123 $line->push( $self->lineage->list );
124 return( $line->reverse->join( '.' ) );
125 }
126 }
127  
128 # Note: HTML::Element compatibility
129 sub all_attr
130 {
131 my $self = shift( @_ );
132 my $ref = $self->attributes;
133 return( %$ref );
134 }
135  
136 # Note: HTML::Element compatibility
137 sub all_attr_names
138 {
139 my $self = shift( @_ );
140 return( $self->attributes->keys->list );
141 }
142  
143 sub as_html { return( shift->as_string( @_ ) ); }
144  
145 sub as_string
146 {
147 my $self = shift( @_ );
148 my $opts = $self->_get_args_as_hash( @_ );
149 # If the element is called from within a collection, although it still has its
150 # parent, we do not know exactly where is its closing tag, if any.
151 # So this option makes it possible to return the tag and its closing tag, if any.
152 $opts->{inside_collection} = 0 if( !CORE::exists( $opts->{inside_collection} ) );
153 $opts->{inside_collection} //= 0;
154 $opts->{recursive} //= 0;
155 return( $self->{_cache_value} ) if( $self->{_cache_value} && !CORE::length( $self->{_reset} ) );
156 my $tag = $self->tag;
157 my $res = $self->new_array;
158 my $a = $self->new_array( ["<${tag}"] );
159 my $hash1 = $self->checksum;
160 my $hash2 = $self->set_checksum;
161 if( $self->original->defined && $hash1 eq $hash2 )
162 {
163 $a->set( [ $self->original->scalar ] );
164 }
165 else
166 {
167 if( !$self->attributes_sequence->is_empty )
168 {
169 my $attr = $self->new_array;
170 $self->attributes_sequence->foreach(sub
171 {
172 my $k = shift( @_ );
173 return(1) if( $k eq '/' );
174 my $v = $self->attributes->get( $k );
175 # Ensure double quotes are escaped
176 $v =~ s/(?<!\\)\"/\\\"/gs;
177 $attr->push( sprintf( '%s="%s"', $k, $v ) );
178 });
179 $a->push( $attr->join( ' ' )->scalar );
180 }
181 }
182 if( !$self->children->is_empty )
183 {
184 if( $self->is_empty )
185 {
186 warn( "This tag \"$tag\" is supposed to be an empty / void one, but it has " . $self->children->length . " children.\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
187 }
188 # The user is alway right, so let's add those children
189 $res->push( $a->join( ' ' )->scalar );
190 $res->push( '>' ) unless( $self->original->defined && $hash1 eq $hash2 );
191 $self->children->foreach(sub
192 {
193 my $e = shift( @_ );
194 my $v;
195 if( $opts->{as_xml} )
196 {
197 $v = $e->as_xml( recursive => 1 );
198 }
199 else
200 {
201 $v = $e->as_string( recursive => 1 );
202 }
203 $res->push( defined( $v ) ? $v->scalar : $v );
204 });
205 # $res->push( "</${tag}>" );
206 # $res->push( "</${tag}>" ) if( !$self->parent && !$self->is_empty );
207 # if( ( $opts->{inside_collection} || !$opts->{recursive} ) && $self->close_tag )
208 if( my $close = $self->close_tag )
209 {
210 my $parent = $self->parent;
211 unless( $parent && defined( my $pos = $parent->children->pos( $close ) ) )
212 {
213 $res->push( $close->as_string );
214 }
215 }
216 }
217 else
218 {
219 if( $self->is_empty )
220 {
221 # No need to add this, because we are re-using the original tag data since it has not changed
222 $a->push( '/>' ) unless( $hash1 eq $hash2 );
223 $res->push( $a->join( ' ' )->scalar );
224 }
225 else
226 {
227 $res->push( $a->join( ' ' )->scalar );
228 $res->push( '>' ) unless( $self->original->defined && $hash1 eq $hash2 );
229 # If it has a parent, the parent will contain the closing tag, but
230 # If this element is an element created with a find, such as $('body'), it has no
231 # parent.
232 # $res->push( "</${tag}>" ) if( !$self->parent && !$self->is_empty );
233 if( my $close = $self->close_tag )
234 {
235 my $parent = $self->parent;
236 unless( $parent && defined( my $pos = $parent->children->pos( $close ) ) )
237 {
238 $res->push( $close->as_string );
239 }
240 }
241 }
242 }
243 my $elem = $res->join( '' );
244 $self->{_cache_value} = $elem;
245 CORE::delete( $self->{_reset} );
246 return( $elem );
247 }
248  
249 # Note: HTML::Element compatibility
250 sub as_text
251 {
252 my $self = shift( @_ );
253 return( $self->{_cache_text} ) if( $self->{_cache_text} && !CORE::length( $self->{_reset} ) );
254 my $opts = $self->_get_args_as_hash( @_ );
255 $opts->{unescape} //= 0;
256 my $a = $self->new_array;
257 my $seen = {};
258 my $crawl;
259 $crawl = sub
260 {
261 my $elem = shift( @_ );
262 $elem->children->foreach(sub
263 {
264 my $e = shift( @_ );
265 my $addr = Scalar::Util::refaddr( $e );
266 return(1) if( CORE::exists( $seen->{ $addr } ) );
267 $seen->{ $addr }++;
268 if( $e->isa( 'HTML::Object::Text' ) ||
269 $e->isa( 'HTML::Object::Space' ) )
270 {
271 if( exists( $opts->{callback} ) && ref( $opts->{callback} ) eq 'CODE' )
272 {
273 # If value returned is not true, we skip this element
274 $opts->{callback}->( $e ) || return(1);
275 }
276 if( $opts->{unescape} )
277 {
278 my $txt = $e->as_string->scalar;
279 $txt =~ s,<br[[:blank:]]*/>\n,\n,gs;
280 $txt =~ s/\&gt;/>/gs;
281 $txt =~ s/\&lt;/</gs;
282 $a->push( $txt );
283 }
284 else
285 {
286 $a->push( $e->as_string->scalar );
287 }
288 }
289
290 unless( $e->isa( 'HTML::Object::Text' ) ||
291 $e->isa( 'HTML::Object::Space' ) )
292 {
293 $crawl->( $e );
294 }
295 });
296 };
297 if( $self->isa( 'HTML::Object::Text' ) ||
298 $self->isa( 'HTML::Object::Space' ) )
299 {
300 if( $opts->{unescape} )
301 {
302 my $txt = $self->value->scalar;
303 $txt =~ s,<br[[:blank:]]*/>\n,\n,gs;
304 $txt =~ s/\&gt;/>/gs;
305 $txt =~ s/\&lt;/</gs;
306 $a->push( $txt );
307 }
308 else
309 {
310 $a->push( $self->value->scalar );
311 }
312 }
313 else
314 {
315 $crawl->( $self );
316 }
317 $self->{_cache_text} = $a->join( '' );
318 CORE::delete( $self->{_reset} );
319 return( $self->{_cache_text} );
320 }
321  
322 # Note: HTML::Element compatibility
323 sub as_trimmed_text
324 {
325 my $self = shift( @_ );
326 my $opts = $self->_get_args_as_hash( @_ );
327 my $text = $self->as_text( $opts ) || return;
328 $text->replace( qr/^[[:blank:]\h\v]+|[[:blank:]\h\v]+$/, '' );
329 return( $text );
330 }
331  
332 # Note: HTML::Element compatibility
333 # This does the same as for html. Sub classes take care of the differences
334 # sub as_xml { return( shift->as_string( @_ ) ); }
335 sub as_xml
336 {
337 my $self = shift( @_ );
338 my $opts = $self->_get_args_as_hash( @_ );
339 $opts->{as_xml} = 1;
340 return( $self->as_string( $opts ) );
341 }
342  
343 sub attr
344 {
345 my $self = shift( @_ );
346 my $attr = shift( @_ ) || return( $self->error( "No attribute name provided." ) );
347 return( $self->error( "Attribute provided \"${attr}\" contains illegal characters. Only alphanumeric and _ are supported." ) ) if( $attr !~ /^\w+$/ );
348 if( @_ )
349 {
350 my $v = shift( @_ );
351 my $old;
352 if( defined( $v ) )
353 {
354 $old = $self->attributes->get( $attr );
355 # We do not want to force stringification, because for attribute like 'href' it could have an URI object as a value.
356 # When stringification will be required, it will be done automatically anyway.
357 # $v = "$v" if( ref( $v ) && overload::Method( $v, '""' ) );
358 $v =~ s/^[[:blank:]\h]+|[[:blank:]\h]+$//g if( !ref( $v ) );
359 $self->attributes->set( $attr => $v );
360 $self->attributes_sequence->push( $attr ) if( !$self->attributes_sequence->has( $attr ) );
361 }
362 else
363 {
364 $self->attributes_sequence->remove( $attr );
365 $old = $self->attributes->delete( $attr );
366 }
367
368 # Check for attributes callback and execute it.
369 # This is typically used for HTML::Object::TokenList by HTML::Object::DOM::Element and HTML::Object::DOM::AnchorElement
370 my $callbacks = $self->{_internal_attribute_callbacks};
371 $callbacks = {} if( ref( $callbacks ) ne 'HASH' );
372 if( CORE::exists( $callbacks->{ $attr } ) && ref( $callbacks->{ $attr } ) eq 'CODE' )
373 {
374 my $cb = $callbacks->{ $attr };
375 # try-catch
376 local $@;
377 eval
378 {
379 $cb->( $self, $v );
380 };
381 if( $@ )
382 {
383 return( $self->error( "Error executing attribute callback for attribute \"$attr\" for element with tag \"", $self->tag, "\": $@" ) );
384 }
385 }
386 $self->reset(1);
387 return( $old );
388 }
389 else
390 {
391 return( $self->attributes->get( $attr ) );
392 }
393 }
394  
395 sub attributes { return( shift->reset(@_)->_set_get_hash_as_mix_object( 'attr', @_ ) ); }
396  
397 sub attributes_sequence
398 {
399 my $self = shift( @_ );
400 unless( @_ )
401 {
402 if( $self->_set_get_array_as_object( 'attr_seq' )->sort != $self->attributes->keys->sort )
403 {
404 $self->_set_get_array_as_object( 'attr_seq', $self->attributes->keys->sort );
405 }
406 }
407 return( $self->reset(@_)->_set_get_array_as_object( 'attr_seq', @_ ) );
408 }
409  
410 sub checksum { return( shift->reset(@_)->_set_get_scalar_as_object( 'checksum', @_ ) ); }
411  
412 sub children { return( shift->reset(@_)->_set_get_object_array_object( 'children', 'HTML::Object::Element', @_ ) ); }
413  
414 sub class { return( ref( $_[0] ) ); }
415  
416 # Note: HTML::Element compatibility
417 sub clone
418 {
419 my $self = shift( @_ );
420 my $new = $self->SUPER::clone();
421 $new->{eid} = $self->_generate_uuid();
422 my $children = $self->clone_list;
423 $new->children( $children );
424 $children->foreach(sub
425 {
426 shift->parent( $new );
427 });
428 $new->parent( undef );
429 $new->reset(1);
430 return( $new );
431 }
432  
433 # Note: HTML::Element compatibility
434 sub clone_list
435 {
436 my $self = shift( @_ );
437 my $a = $self->new_array;
438 $self->children->foreach(sub
439 {
440 my $e = shift( @_ );
441 $a->push( $e->clone );
442 });
443 return( $a );
444 }
445  
446 sub close
447 {
448 my $self = shift( @_ );
449 my $opts = $self->_get_args_as_hash( @_ );
450 # No need to close
451 return( $self ) if( $self->is_empty );
452 # if( !$parent )
453 # {
454 # warn( "No parent set for this element \"" . $self->tag . "\".\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
455 # return( $self );
456 # }
457 my $e = $self->new_closing({
458 attributes => $opts->{attr},
459 attributes_sequence => $opts->{seq},
460 column => $opts->{col},
461 line => $opts->{line},
462 offset => $opts->{offset},
463 original => $opts->{raw},
464 tag => $self->tag,
465 debug => $self->debug,
466 }) || return( $self->pass_error );
467 my $parent = $self->parent;
468 if( $parent )
469 {
470 my $pos = $parent->children->pos( $self );
471 return( $self->error( "Could not find the opening tag '", $self->tag, "' in our parent." ) ) if( !defined( $pos ) );
472 # We place the closing tag in the parent's child right after our opening tag
473 # $parent->children->splice( $pos + 1, 0, $e );
474 }
475 $self->is_closed(1);
476 $self->close_tag( $e );
477 $self->reset(1);
478 return( $self );
479 }
480  
481 sub close_tag { return( shift->reset(@_)->_set_get_object( 'close_tag', 'HTML::Object::Element', @_ ) ); }
482  
483 sub column { return( shift->reset(@_)->_set_get_number_as_object( 'column', @_ ) ); }
484  
485 # Note: HTML::Element compatibility
486 sub content { return( shift->children ); }
487  
488 # Note: HTML::Element compatibility
489 sub content_array_ref { return( shift->children ); }
490  
491 # Note: HTML::Element compatibility
492 sub content_list
493 {
494 my $self = shift( @_ );
495 if( want( 'LIST' ) )
496 {
497 return( $self->children->list );
498 }
499 else
500 {
501 return( $self->children->length );
502 }
503 }
504  
505 # Note: HTML::Element compatibility
506 sub delete
507 {
508 my $self = shift( @_ );
509 $self->delete_content;
510 $self->detach;
511 %$self = ();
512 return;
513 }
514  
515 # Note: HTML::Element compatibility
516 sub delete_content
517 {
518 my $self = shift( @_ );
519 $self->children->foreach(sub
520 {
521 $_->delete;
522 });
523 $self->reset(1);
524 return( $self );
525 }
526  
527 # Note: HTML::Element compatibility
528 # Does not do anything by design
529 sub delete_ignorable_whitespace {}
530  
531 sub depth
532 {
533 my $self = shift( @_ );
534 my $n = 0;
535 my $parent = $self;
536 $n++ while( $parent = $parent->parent );
537 return( $self->new_number( $n ) );
538 }
539  
540 sub descendants
541 {
542 my $self = shift( @_ );
543 my $a = $self->new_array;
544 $self->traverse(sub
545 {
546 my $e = shift( @_ );
547 my $class = $e->class;
548 return(1) unless( $class eq 'HTML::Object::Element' );
549 $a->push( $e );
550 });
551 return( $a );
552 }
553  
554 # Note: HTML::Element compatibility
555 sub destroy { return( shift->delete( @_ ) ); }
556  
557 sub destroy_content { return( shift->delete_content( @_ ) ); }
558  
559 # Note: HTML::Element compatibility
560 sub detach
561 {
562 my $self = shift( @_ );
563 my $parent = $self->parent;
564 return if( !$parent );
565 my $id = $self->eid;
566 my $pos = $parent->children->pos( $self );
567 if( defined( $pos ) )
568 {
569 $parent->children->splice( $pos, 1 );
570 $self->parent( undef() );
571 $parent->reset(1);
572 }
573 return( $parent );
574 }
575  
576 # Note: HTML::Element compatibility
577 sub detach_content
578 {
579 my $self = shift( @_ );
580 $self->children->foreach(sub
581 {
582 shift->parent( undef() );
583 });
584 my @removed = $self->children->list;
585 $self->children->reset;
586 return( @removed );
587 }
588  
589 sub dump
590 {
591 my $self = shift( @_ );
592 my $depth = shift( @_ ) || 0;
593 my $prefix = '.' x $depth;
594 $depth++;
595 my $tag = $self->tag;
596 printf( STDOUT "${prefix} Tag '$tag' has %d children.\n", $self->children->length ) if( $self->children->length );
597 my %esc = (
598 "\a" => "\\a",
599 "\b" => "\\b",
600 "\t" => "\\t",
601 "\n" => "\\n",
602 "\f" => "\\f",
603 "\r" => "\\r",
604 "\e" => "\\e",
605 );
606 $self->children->foreach(sub
607 {
608 my $e = shift( @_ );
609 my $str = $e->original->scalar;
610 $str =~ s/([\a\b\t\n\f\r\e])/$esc{$1}/gs;
611 $str =~ s/([\0-\037])(?!\d)/sprintf('\\%o',ord($1))/eg;
612 $str =~ s/([\0-\037\177-\377])/sprintf('\\x%02X',ord($1))/eg;
613 $str =~ s/([^\040-\176])/sprintf('\\x{%X}',ord($1))/eg;
614 print( STDOUT "${prefix}. ${str}\n" );
615 $e->dump( $depth ) if( !$e->is_empty || $e->children->length );
616 });
617 return( $self );
618 }
619  
620 sub eid { return( shift->{eid} ); }
621  
622 # Returns self, but is overriden in HTML::Object::Collection
623 # See <https://api.jquery.com/end/#end>
624 sub end { return( shift( @_ ) ); }
625  
626 sub extract_links
627 {
628 my $self = shift( @_ );
629 my @tags = @_;
630 for( @tags )
631 {
632 $_ = lc( $_ );
633 }
634 my $wants = {};
635 @$wants{ @tags } = (1) x scalar( @tags );
636 my $has_expectation = scalar( keys( %$wants ) );
637 my $a = $self->new_array;
638 my $crawl;
639 my $seen = {};
640 $crawl = sub
641 {
642 my $kids = shift( @_ );
643 $kids->foreach(sub
644 {
645 my $e = shift( @_ );
646 my $def;
647 my $tag = $e->tag;
648 $def = $HTML::Object::LINK_ELEMENTS->{ "$tag" } if( exists( $HTML::Object::LINK_ELEMENTS->{ "$tag" } ) );
649 # return(1) if( !defined( $def ) );
650 # return(1) if( $has_expectation && !exists( $wants->{ "$tag" } ) );
651 if( defined( $def ) &&
652 (
653 !$has_expectation ||
654 ( $has_expectation && !exists( $wants->{ "$tag" } ) )
655 ) )
656 {
657 foreach my $attr ( @$def )
658 {
659 my $val;
660 if( $e->attributes->exists( $attr ) && length( $val = $e->attributes->get( $attr ) ) )
661 {
662 $a->push( $self->new_hash({
663 attribute => $attr,
664 element => $e,
665 tag => $tag,
666 value => $val,
667 }) );
668 }
669 }
670 }
671 my $addr = Scalar::Util::refaddr( $e );
672 if( ++$seen->{ $addr } > 1 )
673 {
674 return(1);
675 }
676 $crawl->( $e->children );
677 return(1);
678 });
679 };
680 $crawl->( $self->children );
681 return( $a );
682 }
683  
684 # Note: HTML::Element compatibility
685 # sub find { return( shift->find_by_tag_name( @_ ) ); }
686 # find() is a xpath method
687  
688 sub find_by_attribute
689 {
690 my $self = shift( @_ );
691 my( $att, $val ) = @_;
692 $att = lc( $att );
693 return( $self->error( "No attribute was provided." ) ) if( !length( $att ) );
694 my $a = $self->new_array;
695 $a->push( $self ) if( $self->attributes->exists( $att ) && $self->attributes->get( $att ) eq $val );
696 my $crawl;
697 $crawl = sub
698 {
699 my $elems = shift( @_ );
700 $elems->foreach(sub
701 {
702 my $e = shift( @_ );
703 return(1) if( $e->class ne 'HTML::Object::Element' );
704 $a->push( $e ) if( $e->attributes->exists( $att ) && $e->attributes->get( $att ) eq $val );
705 $crawl->( $e->children ) if( $e->children->length > 0 );
706 });
707 };
708 $crawl->( $self->children ) if( $self->children->length > 0 );
709 return( $a );
710 }
711  
712 sub find_by_tag_name
713 {
714 my $self = shift( @_ );
715 my @tags = @_;
716 for( @tags )
717 {
718 $_ = lc( $_ );
719 }
720 my $tags = {};
721 @$tags{ @tags } = (1) x scalar( @tags );
722 my $a = $self->new_array;
723 $a->push( $self ) if( exists( $tags->{ $self->tag } ) );
724 my $crawl;
725 $crawl = sub
726 {
727 my $elems = shift( @_ );
728 $elems->foreach(sub
729 {
730 my $e = shift( @_ );
731 # return(1) if( $e->class ne 'HTML::Object::Element' );
732 return(1) if( !$self->_is_a( $e => 'HTML::Object::Element' ) );
733 $a->push( $e ) if( exists( $tags->{ $e->tag } ) );
734 $crawl->( $e->children ) if( $e->children->length > 0 );
735 });
736 };
737 $crawl->( $self->children ) if( $self->children->length > 0 );
738 return( $a );
739 }
740  
741 sub has_children { return( shift->children->is_empty ? 0 : 1 ); }
742  
743 sub id : lvalue { return( shift->_set_get_id( @_ ) ); }
744  
745 # Note: Similar to HTML::ELement, but not quite, because we have no concept of pos(), so this just add to the stack of children
746 sub insert_element
747 {
748 my $self = shift( @_ );
749 my $e = shift( @_ ) || return( $self->error( "No html element was provided to insert." ) );
750 return( $self->error( "Element provided (", overload::StrVal( $e ), ") is not an object." ) ) if( !$self->_is_object( $e ) );
751 return( $self->error( "Element provided (", overload::StrVal( $e ), ") is not an HTML::Object::Element." ) ) if( !$e->isa( 'HTML::Object::Element' ) );
752 $self->push_content( $e );
753 $self->reset(1);
754 return( $e );
755 }
756  
757 # Used to store arbitrarily data for internal purpose
758 sub internal { return( shift->reset(@_)->_set_get_hash_as_mix_object( '_internal', @_ ) ); }
759  
760 sub is_closed { return( shift->reset(@_)->_set_get_boolean( 'is_closed', @_ ) ); }
761  
762 # Note: Different from HTML::Element in that this is a flag derived from the dictionary. To get the equivalent, one must use has_children()
763 sub is_empty { return( shift->reset(@_)->_set_get_boolean( 'is_empty', @_ ) ); }
764  
765 sub is_valid_attribute { return( $_[1] =~ /^$ATTRIBUTE_NAME_RE$/ ? 1 : 0 ); }
766  
767 sub is_void { return( shift->reset(@_)->is_empty( @_ ) ); }
768  
769 # Note: Compatibility with HTML::Element
770 sub left
771 {
772 my $self = shift( @_ );
773 my $offset = @_ ? int( shift( @_ ) ) : 0;
774 my $pos = $self->pos;
775 # We return empty if we could not find our object within our parent's children; or
776 # the requested offset position is higher than the position of our object
777 return( $self->new_array ) if( !defined( $pos ) || $offset > $pos );
778 my $kids = $self->parent->children;
779 # I am my parent's only child; no need to bother
780 return( $self->new_array ) if( $kids->length == 1 );
781 # We use position as offset length which will put us right before our own element
782 return( $kids->offset( $offset, ( $pos - $offset ) ) );
783 }
784  
785 sub line { return( shift->_set_get_number_as_object( 'line', @_ ) ); }
786  
787 # Note: HTML::Element compatibility
788 sub lineage
789 {
790 my $self = shift( @_ );
791 my $parent = $self;
792 my $lineage = $self->new_array;
793 while( $parent = $parent->parent )
794 {
795 $lineage->push( $parent );
796 }
797 return( $lineage );
798 }
799  
800 sub lineage_tag_names
801 {
802 my $self = shift( @_ );
803 my $a = $self->new_array;
804 my $parent = $self;
805 while( $parent = $parent->parent )
806 {
807 $a->push( $parent->tag->scalar );
808 }
809 return( $a );
810 }
811  
812 sub look
813 {
814 my $self = shift( @_ );
815 my $opts = {};
816 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
817 my $p = [];
818 for( my $i = 0; $i < scalar( @_ ); )
819 {
820 if( ref( $_[$i] ) )
821 {
822 return( $self->error( "Reference provided (", overload::StrVal( $_[$i] ), "), but the only reference I accept is code reference." ) ) if( ref( $_[$i] ) ne 'CODE' );
823 push( @$p, $_[ $i++ ] );
824 }
825 else
826 {
827 push( @$p, {
828 key => $_[$i],
829 val => $_[$i + 1],
830 });
831 $i += 2;
832 }
833 }
834 my $a = $self->new_array;
835 my( $check_elem, $crawl_down );
836 $check_elem = sub
837 {
838 my $e = shift( @_ );
839 my $def = shift( @_ );
840 my $attr = $e->attributes;
841 # Assume ok, then check otherwise
842 my $ok = 1;
843 foreach my $this ( @$p )
844 {
845 if( ref( $this ) eq 'CODE' )
846 {
847 local $_ = $e;
848 my $rc = $this->( $e );
849 $ok = 0, last if( !$rc );
850 }
851 else
852 {
853 if( $this->{key} eq '_tag' )
854 {
855 if( ref( $this->{val} ) eq 'Regexp' )
856 {
857 $ok = 0, last if( $e->tag !~ /$this->{val}/ );
858 }
859 else
860 {
861 $ok = 0, last if( $e->tag ne $this->{val} );
862 }
863 }
864 elsif( !$attr->exists( $this->{key} ) )
865 {
866 if( !defined( $this->{val} ) )
867 {
868 # Good to go; the user searches for an attribute with an undefined value
869 # in other term, the user wants an element whose attribute does not exist
870 }
871 else
872 {
873 $ok = 0, last;
874 }
875 }
876 else
877 {
878 my $val = $attr->get( $this->{key} );
879 if( defined( $val ) )
880 {
881 if( ref( $this->{val} ) eq 'Regexp' )
882 {
883 $ok = 0, last if( $val !~ /$this->{val}/ );
884 }
885 elsif( (
886 ref( $this->{val} ) &&
887 ref( $this->{val} ) ne ref( $val )
888 ) ||
889 (
890 ( !ref( $val ) || overload::Method( $val. '""' ) ) &&
891 lc( "$val" ) ne lc( "$this->{val}" )
892 ) )
893 {
894 $ok = 0, last;
895 }
896 }
897 else
898 {
899 $ok = 0, last if( defined( $this->{val} ) );
900 }
901 }
902 }
903 }
904
905 # We passed all checks, no checking our children
906 $a->push( $e ) if( $ok );
907 # Stop here since we reached the maximum number of matches
908 return if( CORE::exists( $opts->{max_match} ) && $a->length >= $opts->{max_match} );
909 # Don't go down or up further if we reached the maximum level
910 return(1) if( CORE::exists( $opts->{max_level} ) && ( $def->{level} + 1 ) > $opts->{max_level} );
911 $def->{level}++;
912 if( $opts->{direction} eq 'down' )
913 {
914 $crawl_down->( $e->children, $def ) if( $e->children->length > 0 );
915 }
916 elsif( $opts->{direction} eq 'up' )
917 {
918 $check_elem->( $e->parent ) if( $e->parent );
919 }
920 $def->{level}--;
921 return(1);
922 };
923
924 $crawl_down = sub
925 {
926 my $kids = shift( @_ );
927 my $def = shift( @_ );
928 # $kids->foreach( $check_elem );
929 $kids->foreach(sub
930 {
931 $check_elem->( $_, $def );
932 });
933 };
934
935 my $def = { level => 0 };
936 $check_elem->( $self, $def );
937 # return( $a->length > 0 ? $a : '' );
938 return( $a );
939 }
940  
941 sub look_down
942 {
943 my $self = shift( @_ );
944 my $opts = {};
945 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
946 $opts->{direction} = 'down';
947 return( $self->look( @_, $opts ) );
948 }
949  
950 sub look_up
951 {
952 my $self = shift( @_ );
953 my $opts = {};
954 $opts = pop( @_ ) if( ref( $_[-1] ) eq 'HASH' );
955 $opts->{direction} = 'up';
956 return( $self->look( @_, $opts ) );
957 }
958  
959 sub looks_like_html { return( $_[1] =~ /$LOOK_LIKE_HTML/ ? 1 : 0 ); }
960  
961 # sub looks_like_it_has_html { return( $_[1] =~ /$LOOK_LIKE_IT_HAS_HTML/ ? 1 : 0 ); }
962 sub looks_like_it_has_html
963 {
964 my $self = shift( @_ );
965 return( $_[0] =~ /$LOOK_LIKE_IT_HAS_HTML/ ? 1 : 0 );
966 }
967  
968 sub modified { return( shift->_set_get_boolean( 'modified', @_ ) ); }
969  
970 sub new_attribute
971 {
972 my $self = shift( @_ );
973 $self->_load_class( 'HTML::Object::Attribute' ) || return( $self->pass_error );
974 my $att = HTML::Object::Attribute->new( @_ ) ||
975 return( $self->pass_error( HTML::Object::Attribute->error ) );
976 return( $att );
977 }
978  
979 sub new_closing
980 {
981 my $self = shift( @_ );
982 $self->_load_class( 'HTML::Object::Closing' ) || return( $self->pass_error );
983 my $e = HTML::Object::Closing->new( @_ ) ||
984 return( $self->pass_error( HTML::Object::Closing->error ) );
985 return( $e );
986 }
987  
988 sub new_document
989 {
990 my $self = shift( @_ );
991 $self->_load_class( 'HTML::Object::Document' ) || return( $self->pass_error );
992 my $e = HTML::Object::Document->new( debug => $self->debug ) ||
993 return( $self->pass_error( HTML::Object::Document->error ) );
994 return( $e );
995 }
996  
997 sub new_element
998 {
999 my $self = shift( @_ );
1000 my $tag = shift( @_ ) || return( $self->error( "No tag was provided to create an element." ) );
1001 my $dict = HTML::Object->get_definition( $tag ) || return( $self->pass_error( HTML::Object->error ) );
1002 my $e = HTML::Object::Element->new({
1003 is_empty => $dict->{is_empty},
1004 tag => $dict->{tag},
1005 debug => $self->debug,
1006 }) || return( $self->pass_error( HTML::Object::Element->error ) );
1007 return( $e );
1008 }
1009  
1010 sub new_from_lol
1011 {
1012 my $self = shift( @_ );
1013 my $a = $self->new_array;
1014 my @args = @_;
1015 my $crawl;
1016 $crawl = sub
1017 {
1018 my $ref = shift( @_ );
1019 my $parent;
1020 $parent = shift( @_ ) if( scalar( @_ ) );
1021 my $elem;
1022 foreach my $this ( @$ref )
1023 {
1024 if( $self->_is_array( $this ) )
1025 {
1026 my $e = $crawl->( $this, ( $elem // $parent ) ) || return;
1027 if( defined( $elem ) || defined( $parent ) )
1028 {
1029 $e->parent( $elem // $parent );
1030 ( $elem // $parent )->children->push( $e );
1031 }
1032 }
1033 elsif( $self->_is_hash( $this ) )
1034 {
1035 return( $self->error( "Hash of attributes set found before tag name definition" ) ) if( !defined( $elem ) );
1036 $elem->attributes( $this );
1037 }
1038 elsif( $self->_is_object( $this ) && $this->isa( 'HTML::Object::Element' ) )
1039 {
1040 my $custodian = ( $elem // $parent );
1041 my $e = $this->parent ? $this->clone : $this;
1042 return( $self->error( "Found an element object \"", $e->tag, "\" to add to the tree, but no parent was provided nor any element was initiated yet." ) ) if( !defined( $custodian ) );
1043 $e->parent( $custodian );
1044 $custodian->children->push( $e );
1045 }
1046 else
1047 {
1048 return( $self->error( "Found an object ($this), but I do not know what to do with it." ) ) if( $self->_is_object( $this ) && ( !overload::Overloaded( $this ) || ( overload::Overloaded( $this ) && !overload::Method( $this => '""' ) ) ) );
1049 # This is the element tag name
1050 if( !defined( $elem ) && "$this" =~ /^\w+$/ )
1051 {
1052 $elem = $self->new_element( "$this" ) || return;
1053 if( defined( $parent ) )
1054 {
1055 $elem->parent( $parent );
1056 $parent->children->push( $elem );
1057 }
1058 }
1059 # Text node added as a child
1060 else
1061 {
1062 my $custodian = ( $elem // $parent );
1063 return( $self->error( "Found a text to add to the tree, but no parent was provided nor any element was initiated yet." ) ) if( !defined( $custodian ) );
1064 my $t = $self->new_text( "$this" ) || return;
1065 $t->parent( $custodian );
1066 $custodian->children->push( $t );
1067 }
1068 }
1069 }
1070 return( $elem );
1071 };
1072
1073 foreach my $this ( @args )
1074 {
1075 return( $self->error( "I was expecting an array reference, but instead got '$this'." ) ) if( !$self->_is_array( $this ) );
1076 # There are more than one elements provided in this array definition, i.e. multiple html tags at the top level
1077 # so we create a special document html element to contain them
1078 if( scalar( @$this ) > 0 )
1079 {
1080 my $doc = $self->new_document || return;
1081 $crawl->( $this => $doc ) || return;
1082 $a->push( $doc );
1083 }
1084 else
1085 {
1086 my $e = $crawl->( $this ) || return;
1087 $a->push( $e );
1088 }
1089 }
1090 return( $a );
1091 }
1092  
1093 sub new_parser
1094 {
1095 my $self = shift( @_ );
1096 $self->_load_class( 'HTML::Object' ) || return( $self->pass_error );
1097 my $p = HTML::Object->new( debug => $self->debug ) ||
1098 return( $self->pass_error( HTML::Object->error ) );
1099 return( $p );
1100 }
1101  
1102 sub new_text
1103 {
1104 my $self = shift( @_ );
1105 my $p = {};
1106 if( scalar( @_ ) == 1 && ref( $_[0] ) eq 'HASH' )
1107 {
1108 $p = shift( @_ );
1109 }
1110 else
1111 {
1112 $p->{value} = join( '', @_ );
1113 }
1114 $p->{debug} = $self->debug;
1115 $self->_load_class( 'HTML::Object::Text' ) || return( $self->pass_error );
1116 my $e = HTML::Object::Text->new( $p ) ||
1117 return( $self->pass_error( HTML::Object::Text->error ) );
1118 return( $e );
1119 }
1120  
1121 # TODO: next()
1122  
1123 # Note: HTML::Element compatibility
1124 sub normalize_content
1125 {
1126 my $self = shift( @_ );
1127 my $children = $self->children;
1128 my $new = $self->new_array;
1129 my $prev;
1130 $children->foreach(sub
1131 {
1132 if( ( defined( $_ ) && $self->_is_a( $_ => 'HTML::Object::Text' ) && defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) ) ||
1133 ( defined( $_ ) && $self->_is_a( $_ => 'HTML::Object::Space' ) && defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Space' ) ) )
1134 {
1135 $prev->value->append( $_->value );
1136 return(1);
1137 }
1138 $prev = $_;
1139 $new->push( $_ );
1140 });
1141 $self->children( $new );
1142 return( $self );
1143 }
1144  
1145 sub offset { return( shift->reset(@_)->_set_get_number_as_object( 'offset', @_ ) ); }
1146  
1147 sub original { return( shift->_set_get_scalar_as_object( 'original', @_ ) ); }
1148  
1149 sub parent { return( shift->_set_get_object_without_init({
1150 field => 'parent',
1151 weaken => 1,
1152 }, 'HTML::Object::Element', @_ ) ); }
1153  
1154 # Note: Different from the one in HTML::Element
1155 sub pos
1156 {
1157 my $self = shift( @_ );
1158 my $parent = $self->parent;
1159 return( $self->new_null ) if( !$parent );
1160 my $kids = $parent->children;
1161 #my $id = $self->eid;
1162 #my( $pos ) = grep{ $kids->[$_]->eid eq $id } 0..$#$kids;
1163 #return( $pos );
1164 return( $kids->pos( $self ) );
1165 }
1166  
1167 sub pindex { return( shift->pos( @_ ) ); }
1168  
1169 # TODO: previous()
1170  
1171 # Note: HTML::Element compatibility
1172 sub postinsert
1173 {
1174 my $self = shift( @_ );
1175 my $parent = $self->parent;
1176 return( $self->error( "Element has no parent." ) ) if( !$parent );
1177 my $pos = $parent->children->pos( $self );
1178 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1179 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1180 $new->foreach(sub
1181 {
1182 $_->detach if( $_->parent );
1183 $_->parent( $parent );
1184 });
1185 $parent->children->splice( $pos + 1, 0, $new->list );
1186 $parent->reset(1);
1187 return( $self );
1188 }
1189  
1190 # Note: HTML::Element compatibility
1191 sub preinsert
1192 {
1193 my $self = shift( @_ );
1194 my $parent = $self->parent;
1195 return( $self->error( "Element has no parent." ) ) if( !$parent );
1196 my $pos = $parent->children->pos( $self );
1197 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1198 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1199 $new->foreach(sub
1200 {
1201 $_->detach if( $_->parent );
1202 $_->parent( $parent );
1203 });
1204 $parent->children->splice( $pos, 0, $new->list );
1205 $parent->reset(1);
1206 return( $self );
1207 }
1208  
1209 # Note: HTML::Element compatibility
1210 sub push_content
1211 {
1212 my $self = shift( @_ );
1213 return( $self ) unless( @_ );
1214 my $children = $self->children;
1215 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1216 $new->foreach(sub
1217 {
1218 $_->detach if( $_->parent );
1219 $_->parent( $self );
1220 $children->push( $_ );
1221 });
1222 $self->reset(1);
1223 return( $self );
1224 }
1225  
1226 # Note: HTML::Element compatibility
1227 sub replace_with
1228 {
1229 my $self = shift( @_ );
1230 my $parent = $self->parent;
1231 return( $self->error( "Element has no parent." ) ) if( !$parent );
1232 my $pos = $parent->children->pos( $self );
1233 return( $self->error( "Element is not found among parent's children elements." ) ) if( !defined( $pos ) );
1234 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1235 $new->foreach(sub
1236 {
1237 $_->detach if( $_->parent );
1238 $_->parent( $parent );
1239 });
1240 $parent->children->splice( $pos, 1, $new->list );
1241 $parent->reset(1);
1242 return( $self );
1243 }
1244  
1245 sub replace_with_content
1246 {
1247 my $self = shift( @_ );
1248 my $parent = $self->parent;
1249 my $children = $self->children;
1250 return( $self->error( "This element has no parent." ) ) if( !$parent );
1251 my $pos = $parent->children->pos( $self );
1252 return( $self->error( "Unable to find the current element among its parent's children." ) ) if( !defined( $pos ) );
1253 $children->foreach(sub
1254 {
1255 $_->parent( $parent );
1256 });
1257 $parent->splice( $pos, 1, $children->list );
1258 $self->parent( undef() );
1259 $parent->reset(1);
1260 return( $self );
1261 }
1262  
1263 sub reset
1264 {
1265 my $self = shift( @_ );
1266 if( !CORE::length( $self->{_reset} ) && scalar( @_ ) )
1267 {
1268 $self->{_reset} = scalar( @_ );
1269 if( my $parent = $self->parent )
1270 {
1271 $parent->reset(1);
1272 }
1273 }
1274 return( $self );
1275 }
1276  
1277 # Note: HTML::Element compatibility
1278 sub right
1279 {
1280 my $self = shift( @_ );
1281 my $parent = $self->parent;
1282 return( $self->new_null ) if( !$parent );
1283 my $kids = $parent->children;
1284 my $pos = $self->pos;
1285 my $offset = @_ ? int( shift( @_ ) ) : $kids->size;
1286 return( $self->new_array ) if( !defined( $pos ) || $offset < $pos );
1287 return( $self->new_array ) if( $kids->length == 1 );
1288 # my $results = $kids->offset( $pos + 1, ( $offset - $pos ) );
1289 return( $kids->offset( $pos + 1, ( $offset - $pos ) ) );
1290 }
1291  
1292 # Note: HTML::Element compatibility
1293 sub root
1294 {
1295 my $self = shift( @_ );
1296 my $root = $self;
1297 my $parent;
1298 while( $parent = $root->parent )
1299 {
1300 $root = $parent;
1301 }
1302 # Typically a HTML::Object::Document
1303 return( $root );
1304 }
1305  
1306 sub same_as
1307 {
1308 my $self = shift( @_ );
1309 my $elem = shift( @_ ) || return( $self->error( "No element object was provided to compare against." ) );
1310 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is not an object." ) ) if( !$self->_is_object( $elem ) );
1311 return( $self->error( "Element provided (", overload::StrVal( $elem ), ") is not an HTML::Object::Element object." ) ) if( !$elem->isa( 'HTML::Object::Element' ) );
1312 my $my_attr = $self->attributes->keys->sort;
1313 my $her_attr = $elem->attributes->keys->sort;
1314 return(0) unless( $my_attr eq $her_attr );
1315 $my_attr->foreach(sub
1316 {
1317 return(0) if( $self->attributes->get( $_ ) ne $elem->attributes->get( $_ ) );
1318 });
1319 return(0) if( $self->children->length != $elem->children->length );
1320 my $her_kids = $elem->children;
1321 $self->children->for(sub
1322 {
1323 my( $i, $e ) = @_;
1324 return(0) if( !$e->same_as( $her_kids->[$i] ) );
1325 });
1326 return(1);
1327 }
1328  
1329 sub set_checksum
1330 {
1331 my $self = shift( @_ );
1332 my $tag = $self->_tag;
1333 my $a = $self->new_array( [$tag] );
1334 $self->attributes_sequence->foreach(sub
1335 {
1336 my $attr = shift( @_ );
1337 $a->push( $self->attributes->get( $attr ) );
1338 });
1339 return( $self->_get_md5_hash( $a->join( ';' )->scalar ) );
1340 }
1341  
1342 # Note: HTML::Element compatibility
1343 sub splice_content
1344 {
1345 my $self = shift( @_ );
1346 my $offset = shift( @_ );
1347 my $length = shift( @_ );
1348 return( $self ) unless( @_ );
1349 return( $self->error( "Offset value provided '$offset' is not an integer." ) ) if( !$self->_is_integer( $offset ) );
1350 return( $self->error( "Length value provided '$length' is not an integer." ) ) if( !$self->_is_integer( $length ) );
1351 my $children = $self->children;
1352 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1353 $new->foreach(sub
1354 {
1355 $_->detach if( $_->parent );
1356 $_->parent( $self );
1357 });
1358 $children->splice( $offset, $length, $new->list );
1359 $self->reset(1);
1360 return( $self );
1361 }
1362  
1363 sub tag { return( shift->reset(@_)->_set_get_scalar_as_object( 'tag', @_ ) ); }
1364  
1365 # Note: HTML::Element compatibility
1366 sub traverse
1367 {
1368 my $self = shift( @_ );
1369 my $code = shift( @_ ) || return( $self->error( "No code provided to traverse the html tree." ) );
1370 return( $self->error( "The argument provided (", overload::StrVal( $code ), ") is not an anonymous subroutine." ) ) if( ref( $code ) ne 'CODE' );
1371 my $opts = $self->_get_args_as_hash( @_ );
1372 $opts->{bottom_up} //= 0;
1373 my $seen = {};
1374 my $crawl;
1375 $crawl = sub
1376 {
1377 my $e = shift( @_ );
1378 my $addr = Scalar::Util::refaddr( $e );
1379 # Duplicate
1380 return if( ++$seen->{ $addr } > 1 );
1381 local $_ = $e;
1382 $code->( $e ) unless( $opts->{bottom_up} );
1383 $e->children->foreach(sub
1384 {
1385 $crawl->( $_[0] );
1386 });
1387 $code->( $e ) if( $opts->{bottom_up} );
1388 };
1389 $crawl->( $self );
1390 return( $self );
1391 }
1392  
1393 # Note: HTML::Element compatibility
1394 sub unshift_content
1395 {
1396 my $self = shift( @_ );
1397 return( $self ) unless( @_ );
1398 my $children = $self->children;
1399 my $new = $self->_get_elements_list( @_ ) || return( $self->pass_error );
1400 $new->foreach(sub
1401 {
1402 $_->parent( $self );
1403 });
1404 $children->splice( 0, 0, $new->list );
1405 $self->reset(1);
1406 return( $self );
1407 }
1408  
1409 # called on a parent, with a child as second argument and its rank as third
1410 # returns the child if it is already an element, or
1411 # a new HTML::Object::Text element if it is a plain string
1412 sub _child_as_object
1413 {
1414 my( $self, $elt_or_text, $rank ) = @_;
1415 return unless( defined( $elt_or_text ) );
1416 if( !ref( $elt_or_text ) )
1417 {
1418 require HTML::Object::Text;
1419 # $elt_or_text is a string, turn it into a TextNode object
1420 $elt_or_text = HTML::Object::Text->new(
1421 parent => $self,
1422 value => $elt_or_text,
1423 );
1424 }
1425 warn( "rank is a ", ref( $rank ), " elt_or_text is a ", ref( $elt_or_text ) ) if( ref( $rank ) && !$self->_is_a( $rank, 'Module::Generic::Number' ) );
1426 # used for sorting
1427 $elt_or_text->rank( $rank );
1428 return( $elt_or_text );
1429 }
1430  
1431 sub _generate_uuid
1432 {
1433 return( lc( Data::UUID->new->create_str ) );
1434 }
1435  
1436 sub _get_elements_list
1437 {
1438 my $self = shift( @_ );
1439 my $new = $self->new_array;
1440 my $seen = {};
1441 my $prev;
1442 my $self_addr = Scalar::Util::refaddr( $self );
1443 my $parent_addr;
1444 my $parent = $self->parent;
1445 $parent_addr = Scalar::Util::refaddr( $parent ) if( defined( $parent ) );
1446 for( @_ )
1447 {
1448 return( $self->error( "Replacement element is not an HTML::Object::Element" ) ) if( !$self->_is_a( $_ => 'HTML::Object::Element' ) );
1449 my $addr = Scalar::Util::refaddr( $_ );
1450 if( ++$seen->{ $addr } > 1 )
1451 {
1452 warn( "Warnings only: found duplicate element with tag '" . $_->tag . "' provided in replace_with()\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
1453 next;
1454 }
1455 return( $self->error( "Replacement list contains a copy of target!" ) ) if( $self_addr eq $addr );
1456 return( $self->error( "Cannot replace an item with its parent!" ) ) if( defined( $parent_addr ) && $addr eq $parent_addr );
1457 if( ( $_->isa( 'HTML::Object::Text' ) && defined( $prev ) && $prev->isa( 'HTML::Object::Text' ) ) ||
1458 ( $_->isa( 'HTML::Object::Space' ) && defined( $prev ) && $prev->isa( 'HTML::Object::Space' ) ) )
1459 {
1460 $prev->value->append( $_->value );
1461 next;
1462 }
1463 $new->push( $_ );
1464 $prev = $_;
1465 }
1466 return( $new );
1467 }
1468  
1469 # Used by after, append, before
1470 sub _get_from_list_of_elements_or_html
1471 {
1472 my $self = shift( @_ );
1473 my $list = $self->new_array;
1474 my $prev;
1475 foreach my $this ( @_ )
1476 {
1477 if( $self->_is_a( $this => 'HTML::Object::Element' ) )
1478 {
1479 if( $self->_is_a( $this => 'HTML::Object::DOM::DocumentFragment' ) )
1480 {
1481 my $clone = $this->children->clone;
1482 $list->push( $clone->list );
1483 $this->children->reset;
1484 undef( $prev );
1485 }
1486 elsif( $self->_is_a( $this => 'HTML::Object::Text' ) )
1487 {
1488 if( defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) )
1489 {
1490 $prev->value->append( $this->value );
1491 }
1492 else
1493 {
1494 my $clone = $this->clone;
1495 $list->push( $clone );
1496 $prev = $clone;
1497 }
1498 }
1499 else
1500 {
1501 my $clone = $this->clone;
1502 $list->push( $clone );
1503 # $list->push( $clone->close_tag ) if( $clone->close_tag );
1504 undef( $prev );
1505 }
1506 }
1507 else
1508 {
1509 if( ref( $this ) && ( !$self->_is_object( $this ) || ( $self->_is_object( $this ) && !overload::Method( $this, '""' ) ) ) )
1510 {
1511 return( $self->error( "I was expecting some HTML data, but got '", overload::StrVal( $this ), "'" ) );
1512 }
1513
1514 # if( "$this" =~ /$LOOK_LIKE_HTML/ )
1515 # LOOK_LIKE_HTML check for html tag starting at the beginning of the string
1516 # LOOK_LIKE_IT_HAS_HTML checks for tag anywhere
1517 if( "$this" =~ /$LOOK_LIKE_IT_HAS_HTML/ )
1518 {
1519 my $p = $self->new_parser( debug => 4 );
1520 my $res = $p->parse_data( "$this" ) ||
1521 return( $self->error( "Error while parsing html data provided: ", $p->error ) );
1522 $list->push( $res->children->list ) if( !$res->children->is_empty );
1523 }
1524 # Maybe just some text provided, and in that case, the parser would return nothing unfortunately
1525 else
1526 {
1527 if( defined( $prev ) && $self->_is_a( $prev => 'HTML::Object::Text' ) )
1528 {
1529 $prev->value->append( "$this" );
1530 }
1531 else
1532 {
1533 my $e = $self->new_text({ value => "$this" });
1534 $list->push( $e );
1535 $prev = $e;
1536 }
1537 }
1538 }
1539 }
1540 return( $list );
1541 }
1542  
1543 sub _get_md5_hash
1544 {
1545 my $self = shift( @_ );
1546 my $data = shift( @_ );
1547 return( $self->error( "No data was provided to compute a md5 hash." ) ) if( !defined( $data ) || !length( "$data" ) );
1548 # try-catch
1549 local $@;
1550 my $rv = eval
1551 {
1552 return( Digest::MD5::md5_hex( Encode::encode( 'utf8', $data, Encode::FB_CROAK ) ) );
1553 };
1554 if( $@ )
1555 {
1556 return( $self->error( "An error occurred while calculating the md5 hash for tag \"", $self->tag, "\": $@" ) );
1557 }
1558 return( $rv );
1559 }
1560  
1561 # For other modules to use
1562 sub _is_reset { return( CORE::length( shift->{_reset} ) ); }
1563  
1564 # For other modules to use
1565 sub _remove_reset { return( CORE::delete( shift->{_reset} ) ); }
1566  
1567 # Method shared with HTML::Object::XQuery
1568 sub _set_get_id : lvalue { return( shift->_set_get_callback({
1569 get => sub
1570 {
1571 my $self = shift( @_ );
1572 my $id = $self->new_scalar( $self->attributes->get( 'id' ) );
1573 return( $id );
1574 },
1575 set => sub
1576 {
1577 my $self = shift( @_ );
1578 my $id = shift( @_ );
1579 if( !defined( $id ) || !CORE::length( $id ) )
1580 {
1581 if( $self->attributes->exists( 'id' ) )
1582 {
1583 $self->attributes->delete( 'id' );
1584 $self->attributes_sequence->remove( 'id' );
1585 $self->reset(1);
1586 return(1);
1587 }
1588 return(0);
1589 }
1590 else
1591 {
1592 $self->attributes->set( id => $id );
1593 $self->reset(1);
1594 return(1);
1595 }
1596 }
1597 }, @_ ) ); }
1598  
1599 sub _same_as
1600 {
1601 my $self = shift( @_ );
1602 my $this = shift( @_ );
1603 return(0) if( !defined( $this ) || ( defined( $this ) && !$self->_is_a( $this, 'HTML::Object::Element' ) ) );
1604 return( $self->eid CORE::eq $this->eid ? 1 : 0 );
1605 }
1606  
1607 # Used to register callbacks for some properties like rel, sizes, controlslist that we trigger and that update the attribute's HTML::Object::TokenList
1608 sub _set_get_internal_attribute_callback
1609 {
1610 my $self = shift( @_ );
1611 $self->{_internal_attribute_callbacks} = {} if( ref( $self->{_internal_attribute_callbacks} ) ne 'HASH' );
1612 my $ref = $self->{_internal_attribute_callbacks};
1613 # get mode
1614 if( scalar( @_ ) == 1 )
1615 {
1616 my $attr = shift( @_ );
1617 return( $ref->{ $attr } );
1618 }
1619 elsif( scalar( @_ ) )
1620 {
1621 return( $self->error( "Odd number of parameters for attribute callback assignment." ) ) if( ( @_ % 2 ) );
1622 for( my $i = 0; $i < scalar( @_ ); $i += 2 )
1623 {
1624 $ref->{ $_[ $i ] } = $_[ $i + 1 ];
1625 }
1626 return( $self );
1627 }
1628 return;
1629 }
1630  
1631 # A private method for internal use when the tag method has been overriden for example as it is the case in HTML::Object::XQuery
1632 sub _tag { return( shift->reset(@_)->_set_get_scalar_as_object( 'tag', @_ ) ); }
1633  
1634 1;
1635 # NOTE: POD
1636 __END__
1637  
1638 =encoding utf-8
1639  
1640 =head1 NAME
1641  
1642 HTML::Object::Element - HTML Element Object
1643  
1644 =head1 SYNOPSIS
1645  
1646 use HTML::Object::Element;
1647 my $this = HTML::Object::Element->new ||
1648 die( HTML::Object::Element->error, "\n" );
1649  
1650 =head1 VERSION
1651  
1652 v0.3.0_1
1653  
1654 =head1 DESCRIPTION
1655  
1656 This interface implement a core element for L<HTML::Object> parser. An element can be one or more space, a text, a tag, a comment, or a document, all of the above inherit from this core interface.
1657  
1658 For a more elaborate interface and a close implementation of the Web Document Object Model (a.k.a. DOM), see L<HTML::Object::DOM::Element> and the L<DOM parser|HTML::Object::DOM>
1659  
1660 =head1 METHODS
1661  
1662 =for Pod::Coverage add
1663  
1664 =for Pod::Coverage addClass
1665  
1666 =for Pod::Coverage appendTo
1667  
1668 =for Pod::Coverage align
1669  
1670 =for Pod::Coverage compact
1671  
1672 =for Pod::Coverage crossOrigin
1673  
1674 =for Pod::Coverage currentSrc
1675  
1676 =for Pod::Coverage defaultValue
1677  
1678 =for Pod::Coverage download
1679  
1680 =for Pod::Coverage form
1681  
1682 =for Pod::Coverage hash
1683  
1684 =for Pod::Coverage host
1685  
1686 =for Pod::Coverage hostname
1687  
1688 =for Pod::Coverage href
1689  
1690 =for Pod::Coverage hreflang
1691  
1692 =for Pod::Coverage origin
1693  
1694 =for Pod::Coverage password
1695  
1696 =for Pod::Coverage pathname
1697  
1698 =for Pod::Coverage port
1699  
1700 =for Pod::Coverage protocol
1701  
1702 =for Pod::Coverage referrerPolicy
1703  
1704 =for Pod::Coverage rel
1705  
1706 =for Pod::Coverage relList
1707  
1708 =for Pod::Coverage search
1709  
1710 =for Pod::Coverage setCustomValidity
1711  
1712 =for Pod::Coverage target
1713  
1714 =for Pod::Coverage useMap
1715  
1716 =for Pod::Coverage username
1717  
1718 =head2 address
1719  
1720 This method is purely for compatibility with L<HTML::Element/address>. Please, refer to its documentation for its use.
1721  
1722 =head2 all_attr
1723  
1724 Returns an hash (B<not> an hash reference) of the element's attributes as a key-value pairs.
1725  
1726 This is provided in compatibility with C<HTML::Element>
1727  
1728 my %attributes = $e->all_attr;
1729  
1730 =head2 all_attr_names
1731  
1732 Returns a list of all the element's attributes in no particular order.
1733  
1734 my @attributes = $e->all_attr_names;
1735  
1736 =head2 as_html
1737  
1738 This is an alias for L</as_string>
1739  
1740 =head2 as_string
1741  
1742 Returns a string representation of the current element and its underlying descendants.
1743  
1744 If a cached version of that string exists, it is returned instead.
1745  
1746 =head2 as_text
1747  
1748 Returns a string representation of the text content of the current element and its descendant.
1749  
1750 If a cached version of that string exists, it is returned instead.
1751
1752 It takes an optional hash or hash reference of parameters:
1753  
1754 =over 4
1755  
1756 =item * C<callback>
1757  
1758 This is a callback subroutine reference of anonymous subroutine. It is called for each textual element found and is passed as its sole argument, the element object.
1759  
1760 =item * C<unescape>
1761  
1762 Boolean. If true, the value of textual elements found will be unescaped before being returned. This means that C<< &lt; >> will be converted back to C<< < >> and C<< &gt; >> to C<< > >> and C<< <br > >> followed by a new line will be removed to only leave the new line.
1763  
1764 =back
1765  
1766 See also L<HTML::Object::DOM::Element/innerText>, L<HTML::Object::Node/textContent> and L<HTML::Object::XQuery/text>
1767  
1768 =head2 as_trimmed_text
1769  
1770 Return the value returned by L</as_text>, only its leading and trailing spaces, if any, are trimmed.
1771  
1772 =head2 as_xml
1773  
1774 This is merely an alias for L<as_string>
1775  
1776 =head2 attr
1777  
1778 Provided with an attribute C<name> and this will return it. If an attribute C<value> is also provided, it will set or replace the attribute valu accordingly. If that attribute value provided is C<undef>, this will remove the attribute altogether.
1779  
1780 =head2 attributes
1781  
1782 Returns an L<hash object|Module::Generic::Hash> of all the attributes key-value pairs.
1783  
1784 Be careful this is a 'live' object, and if you make change to it directly, you could damage the hierarchy or introduce errors.
1785  
1786 =head2 attributes_sequence
1787  
1788 Returns an L<array object|Module::Generic::Array> containing the attribute names in their order of appearance.
1789  
1790 =head2 checksum
1791  
1792 Returns the element checksum, used to determine if any change was made.
1793  
1794 =head2 children
1795  
1796 Returns an L<array object|Module::Generic::Array> containing all the element's children.
1797  
1798 =head2 class
1799  
1800 Returns this element class, e.g. C<HTML::Object::Element> or C<HTML::Object::Document>
1801  
1802 =head2 clone
1803  
1804 Returns a copy of the current element, and recursively all of its descendants,
1805  
1806 The cloned element, that is returned, has no parent.
1807  
1808 =head2 clone_list
1809  
1810 Clone all the element children and return a new L<array object|Module::Generic::Array> of the cloned children.
1811  
1812 This is quite different from C<HTML::Element> equivalent that is accessed as a class method and takes an arbitrary list of elements.
1813  
1814 =head2 close
1815  
1816 Close the current tag, if necessary. It returns the current object upon success, or C<undef> upon error and sets an L<error|Module::Generic/error>
1817  
1818 =head2 close_tag
1819  
1820 Set or get a L<closing element object|HTML::Object::Closing> that is used to close the current element.
1821  
1822 =head2 column
1823  
1824 Returns the column at which this element was found in the original HTML text string, by the L<parser|HTML::Object>.
1825  
1826 =head2 content
1827  
1828 This is an alias for L</children>. It returns an L<array object|Module::Generic::Array> of the current element's children objects.
1829  
1830 =head2 content_array_ref
1831  
1832 This is an alias for L</children>. It returns an L<array object|Module::Generic::Array> of the current element's children objects.
1833  
1834 This is provided in compatibility with C<HTML::Element>
1835  
1836 =head2 content_list
1837  
1838 In list context, this returns the list of the curent element's children, if any, and in scalar context, this returns the number of children elements it contains.
1839  
1840 This is provided in compatibility with C<HTML::Element>
1841  
1842 =head2 delete
1843  
1844 Remove all of its content by calling L</delete_content>, detach the current object, and destroy the object.
1845  
1846 =head2 delete_content
1847  
1848 Remove the content, i.e. all the children, of the current element, effectively calling L</delete> on each one of them.
1849  
1850 It returns the current element.
1851  
1852 =head2 delete_ignorable_whitespace
1853  
1854 Does not do anything by design. There is no much value into this method under L<HTML::Object> in the first place.
1855  
1856 =head2 depth
1857  
1858 Returns an L<integer|Module::Generic::Number> representing the depth level of the current element in the hierarchy.
1859  
1860 =head2 descendants
1861  
1862 Returns an L<array object|Module::Generic::Array> of all the element's descendants throughout its hierarchy.
1863  
1864 =head2 destroy
1865  
1866 An alias for L</delete>
1867  
1868 =head2 destroy_content
1869  
1870 An alias for L</delete_content>
1871  
1872 =head2 detach
1873  
1874 This method takes no parameter and removes the current element from its parent's list of children element, and unset its parent object value.
1875  
1876 It returns the element parent object.
1877  
1878 =head2 detach_content
1879  
1880 This method takes no argument and will remove the parent value for each of its children, set the children list for the current element to an empty list and return the list of those children elements thus removed.
1881  
1882 my @removed = $e->detach_content;
1883  
1884 This is provided in compatibility with C<HTML::Element>
1885  
1886 =head2 dump
1887  
1888 Print out on the stdout a representation of the hierarchy of element objects.
1889  
1890 =head2 eid
1891  
1892 Returns the element unique id, which is automatically generated for any element. This is actually a uuid. For example:
1893  
1894 my $eid = $e->eid; # e.g.: 971ef725-e99b-4869-b6ac-b245794e84e2
1895  
1896 =head2 end
1897  
1898 Returns the current object.
1899  
1900 Actually, I am not sure this should be here, and rather it should be in L<HTML::Object::XQuery> since it simulates jQuery.
1901  
1902 =head2 extract_links
1903  
1904 Returns links found by traversing the element and all of its children and looking for attributes (like C<href> in an C<<a>> element, or C<src> in an C<<img>> element) whose values represent links.
1905  
1906 You may specify that you want to extract links from just some kinds of elements (instead of the default, which is to extract links from all the kinds of elements known to have attributes whose values represent links). For instance, if you want to extract links from only C<<a>> and C<<img>> elements, you could code it like this:
1907  
1908 my $links = $elem->extract_links( qw( a img ) ) ||
1909 die( $elem->error );
1910 foreach( @$links )
1911 {
1912 say "Hey, there is a ", $_->{tag}, " that links to ", $_->{value}, "in its ", $_->{attribute}, " attribute, at ", $_->{element}->address;
1913 }
1914  
1915 The dictionary definition hash reference of all tags and their attributes containing potential links is available as C<$HTML::Object::LINK_ELEMENTS>
1916  
1917 This method returns an L<array object|Module::Generic::Array> containing L<hash objects|Module::Generic::Hash>, for each attribute of an element containing a link, with the following properties:
1918  
1919 =over 4
1920  
1921 =item * C<attribute>
1922  
1923 The attribute containing the link
1924  
1925 =item * C<element>
1926  
1927 The L<element object|HTML::Object::Element>
1928  
1929 =item * C<tag>
1930  
1931 The element tag name.
1932  
1933 =item * C<value>
1934  
1935 The attribute value, which would typically contain the link value.
1936  
1937 =back
1938  
1939 Nota bene: this method has been implemented to provide similar API as L<HTML::Element> and the 2 first paragraphs of this method description are taken from this module.
1940  
1941 =head2 find_by_attribute
1942  
1943 Returns an L<array object|Module::Generic::Array> of all the elements (including potentially the current element itself) in the element's hierarchy who have an attribute that matches the given attribute name.
1944  
1945 my $list = $e->find_by_attribute( 'data-dob' );
1946  
1947 =head2 find_by_tag_name
1948  
1949 Returns an L<array object|Module::Generic::Array> of all the elements (including potentially the current element itself) in the element's hierarchy who matches any of the specified tag names. Tag names can be provided n case insensitive.
1950  
1951 my $list = $e->find_by_tag_name( qw( div p span ) );
1952  
1953 =head2 has_children
1954  
1955 Returns true if the current element has children, i.e. it contains other elements within itself.
1956  
1957 =head2 id
1958  
1959 Set or get the id HTML attribute of the element.
1960  
1961 =head2 insert_element
1962  
1963 Provided with an element object and this will add it to the current element's children.
1964  
1965 It returns the current element object.
1966  
1967 =head2 internal
1968  
1969 Returns the internal hash of key-value paris used internally by this package. This is primarily used to handle the C<data-*> special attributes.
1970  
1971 =head2 is_closed
1972  
1973 Returns true if the current element has a L<closing tag|HTML::Object::Closing> that is accessible with L</close_tag>
1974  
1975 =head2 is_empty
1976  
1977 Returns true if this is an element who, by HTML standard, does not contain any other elements, and false otherwise.
1978  
1979 To check if the element has children, use L</has_children>
1980  
1981 =head2 is_inside
1982  
1983 Provided with a list of tag names or element objects, and this will check if the current element is contained in any of the element objects, or elements whose tag name is provided. It returns true if it is contained, or false otherwise.
1984  
1985 Example:
1986  
1987 say $e->is_inside( qw( span div ), $elem1, 'p', $elem2 ) ? 'yes' : 'no';
1988  
1989 =head2 is_valid_attribute
1990  
1991 Provided with an attribute name and this returns true if it is valid of false otherwise.
1992  
1993 =head2 is_void
1994  
1995 Returns true if, by standard, this tag is void, meaning it does not contain any children. For example: C<<br />>, C<<link />>, or C<<input />>
1996  
1997 =head2 left
1998  
1999 Returns an L<array object|Module::Generic::Array> of all the sibling objects before the current element.
2000  
2001 =head2 line
2002  
2003 Returns the line at which this element was found in the original HTML text string, by the L<parser|HTML::Object>.
2004  
2005 =head2 lineage
2006  
2007 Returns an L<array object|Module::Generic::Array> of the current element's parent and parent's parent up to the L<root of the hierarchy|HTML::Object::Document>
2008  
2009 =head2 lineage_tag_names
2010  
2011 Returns an L<array object|Module::Generic::Array> of the current element's parent tag name and parent's parent tag name up to the L<root of the hierarchy|HTML::Object::Document>
2012  
2013 This is equivalent to:
2014  
2015 my $list = $self->lineage->map(sub{ $_->tag });
2016  
2017 =head2 look
2018  
2019 This is the method that does the heavy work for L</look_down> and L</look_up>
2020  
2021 =head2 look_down
2022  
2023 Provided with some criterias, and an optional hash reference of options, and this will crawl down the current element hierarchy to find any matching element.
2024  
2025 my $list = $e->look_down( _tag => 'div' ); # returns an Module::Generic::Array object
2026 my $list = $e->look_down( class => qr/\bclass_name\b/, { max_level => 3, max_match => 1 });
2027  
2028 The options you can specify are:
2029  
2030 =over 4
2031  
2032 =item I<max_level>
2033  
2034 Takes an integer that sets the maximum lower or upper level beyond which, this wil stop searching.
2035  
2036 =item I<max_match>
2037  
2038 Takes an integer that sets the maximum number of matches after which, this will stop recurring and return the result.
2039  
2040 =back
2041  
2042 There are three kinds of criteria you can specify:
2043  
2044 =over 4
2045  
2046 =item 1. C<attr_name>, C<attr_value>
2047  
2048 This is used when you are looking for an element with a particular attribute name and value. For example:
2049  
2050 my $list = $e->look_down( id => 'hello' );
2051  
2052 This will look for any element whose attribute C<id> has a value of C<hello>
2053  
2054 If you want to search for an attribute that does B<not> exist, set the attribute value being searched to C<undef>
2055  
2056 To search for a tag, use the special attribute C<_tag>. For example:
2057  
2058 my $list = $e->look_down( _tag => 'div' );
2059  
2060 This will return an L<array object|Module::Generic::Array> of all the C<div> elements.
2061  
2062 =item 2. C<attr_name>, qr//
2063  
2064 Same as above, except the attribute value of the element being checked will be evaluated against this regular expression and if true will be added into the resulting array object.
2065  
2066 For example:
2067  
2068 my $list = $e->look_down( 'data-dob' => qr/^\d{4}-\d{2}-\d{2}$/ );
2069  
2070 This will search for all element who have an attribute C<data-dob> and with value something that looks like a date.
2071  
2072 =item 3. \&my_check or sub{ # some code here }
2073  
2074 Provided with a code reference (i.e. a reference to an existing subroutine, or an anonymous one), and it will be evaluated for each element found. If it returns C<undef>, C<look_down> will interrupt its crawling, and if it returns true, it will signal the need to add the element to the resulting array object of elements.
2075  
2076 For example:
2077  
2078 my $list = $e->look_down(
2079 _tag => 'img',
2080 class => qr/\bactive\b/,
2081 sub
2082 {
2083 return( $_->attr( 'width' ) > 350 ? 1 : 0 );
2084 }
2085 );
2086  
2087 When executing the code, the current element being evaluated will be made available via C<$_>
2088  
2089 =back
2090  
2091 Those criteria are called and evaluated in the order they are provided. Thus, if you specify, for example:
2092  
2093 my $list = $e->look_down(
2094 _tag => 'img',
2095 class => qr/\bactive\b/,
2096 sub
2097 {
2098 return( $_->attr( 'width' ) > 350 ? 1 : 0 );
2099 }
2100 );
2101  
2102 Each element will be evaluated first to see if their tag is C<img> and discarded if they are not. Then, if they have a class attribute and its content match the regular expression provided, and the element gets discarded if it does not match. Finally, the code will be evaluated.
2103  
2104 Thus, the order of the criteria is important.
2105  
2106 It returns an L<array object|Module::Generic::Array> of all the elements found.
2107  
2108 This is provided as a compatibility with C<HTML::Element>
2109  
2110 =head2 look_up
2111  
2112 Provided with some criterias, and an optional hash reference of options, and this will crawl up the current element ascendants starting with its parent to find any matching element.
2113  
2114 The options that can be used are the same ones that for L</look_down>, i.e. C<max_level> and C<max_match>
2115  
2116 It returns an L<array object|Module::Generic::Array> of all the elements found.
2117  
2118 This is provided as a compatibility with C<HTML::Element>
2119  
2120 =head2 looks_like_html
2121  
2122 Provided with a string and this returns true if the string starts with an HTML tag, or false otherwise.
2123  
2124 =head2 looks_like_it_has_html
2125  
2126 Provided with a string and this returns true if the string contains HTML tags, or false otherwise.
2127  
2128 =head2 modified
2129  
2130 Set or get a boolean of whether the element was modified. Actually this is not used.
2131  
2132 This returns a L<DateTime> object.
2133  
2134 =head2 new_attribute
2135  
2136 This creates a new L<HTML::Object::Attribute> object passing it any arguments provided, and returns the object thus created, or C<undef> if an L<error|Module::Generic/error> occurred.
2137  
2138 =head2 new_closing
2139  
2140 This creates a new L<HTML::Object::Closing> object passing it any arguments provided, and returns the object thus created, or C<undef> if an L<error|Module::Generic/error> occurred.
2141  
2142 =head2 new_document
2143  
2144 Instantiate a new L<HTML document|HTML::Object::Document>, passing it whatever argument was provided, and return the resulting object.
2145  
2146 =head2 new_element
2147  
2148 Instantiate a new L<element|HTML::Object::Element>, passing it whatever argument was provided, and return the resulting object.
2149  
2150 =head2 new_from_lol
2151  
2152 This is a legacy from C<HTML::Element>, but is not actually used.
2153  
2154 This recursively constructs a tree of nodes.
2155  
2156 It returns an L<array object|Module::Generic::Array> of elements.
2157  
2158 =head2 new_parser
2159  
2160 Instantiate a new L<parser object|HTML::Object>, passing it whatever argument was provided, and return the resulting object.
2161  
2162 =head2 new_text
2163  
2164 Instantiate a new L<text object|HTML::Object::Text>, passing it whatever argument was provided, and return the resulting object.
2165  
2166 =head2 normalize_content
2167  
2168 Check each of the current element child element and concatenate any adjacent text or space element.
2169  
2170 It returns the current object.
2171  
2172 =head2 offset
2173  
2174 Returns the offset value, i.e. the byte position, at which the tag was found in the original HTML data.
2175  
2176 =head2 original
2177  
2178 Returns the original raw string data as it was captured initially by the parser.
2179  
2180 This is an important feature of L<HTML::Object> since that, if nothing was changed, L<HTML::Object> will return the element objects in their C<original> text version.
2181  
2182 Whereas, other HTML parser, decode all the HTML elements parsed and rebuild them, often badly and even though they have not been changed, which of course, incur a heavy speed penalty.
2183  
2184 =head2 parent
2185  
2186 Returns the current element's L<parent element|HTML::Object::Element>, if any. The value returned could very well be empty if, for example, it is the L<top element|HTML::Object::Document> or if the element was created independently of any parsing.
2187  
2188 =head2 pindex
2189  
2190 This is an alias for L</pos>
2191  
2192 =head2 pos
2193  
2194 Read-only.
2195  
2196 Returns the position L<integer|Module::Generic::Number> of the current element among its parent's children elements.
2197  
2198 It returns a L<smart undef|Module::Generic/new_null> if the element has no parent.
2199  
2200 If the current element, somehow, could not be found among its parent, this would return C<undef>
2201  
2202 Contrary to the C<HTML::Element> equivalent, you cannot manually change this value.
2203  
2204 =head2 postinsert
2205  
2206 Provided with a list of L<elements|HTML::Object::Element> and this will add them right after the current element in its parent's children.
2207  
2208 It returns the current element object for chaining upon success, and upon error, it returns C<undef> and sets an L<error|HTML::Object::Exception>
2209  
2210 =head2 preinsert
2211  
2212 Provided with a list of L<elements|HTML::Object::Element> and this will add them right before the current element in its parent's children.
2213  
2214 It returns the current element object for chaining upon success, and upon error, it returns C<undef> and sets an L<error|HTML::Object::Exception>
2215  
2216 =head2 push_content
2217  
2218 Provided with a list of L<elements|HTML::Object::Element> and this will add them as children to the current element.
2219  
2220 Contrary to the C<HTML::Element> equivalent, this requires that only object be provided, which is easy to do anyhow.
2221  
2222 If consecutive text or space objects are provided they are automatically merged with their immediate text or space objects, if any.
2223  
2224 For example:
2225  
2226 $e->push_content( $elem1, HTML::Object::Element->new( value => q{some text} ), $elem2 );
2227  
2228 And if two consecutive text objects were provided the second one would have its L<value|HTML::Object::Text/value> merged with the previous one.
2229  
2230 It returns the current element object for chaining.
2231  
2232 =head2 replace_with
2233  
2234 Provided with a list of L<element objects|HTML::Object::Element> and this will replace the current element in its parent's children with the element objects provided.
2235  
2236 This will return an L<error|HTML::Object::Exception> if the current element has no parent, or if the current element cannot be found among its parent's children elements.
2237  
2238 Also, this method will filter out any duplicate objects, and return an error if the element being replaced is also among the objects provided for replacement or if the current element's parent is among the replacement objects.
2239  
2240 Each replacement object is detached from its previous parent and re-attach to the current element's parent before being added to its children.
2241  
2242 It returns the current element object.
2243  
2244 =head2 replace_with_content
2245  
2246 Replaces the current element in its parent's children by its own children element, which, in other words, means that the current element children will be moved up and replace the current element itself.
2247  
2248 It returns the current element object, which will then, have no more parent.
2249  
2250 =head2 reset
2251  
2252 Enable the reset flag for this element, which has the effect of instructing L</as_string> to not use its cache.
2253  
2254 =head2 right
2255  
2256 Returns an L<array object|Module::Generic::Array> of all the sibling objects after the current element.
2257  
2258 =head2 root
2259  
2260 Returns the top most element in the hierarchy, which usually is L<HTML::Object::Document>
2261  
2262 =head2 same_as
2263  
2264 This method will check that 2 element objects are similar, in the sense that they can have different L</eid>, but have identical structure.
2265  
2266 I you want to check if 2 element object are actually the same, by comparing their C<eid>, you can use the comparison signs that have been overloaded. For example:
2267  
2268 say $a eq $b ? 'same' : 'nope';
2269  
2270 =head2 set_checksum
2271  
2272 Calculate and returns the md5 checksum of the current element based on all its attributes.
2273  
2274 =head2 splice_content
2275  
2276 Provided with an C<offset> and a C<length>, and a list of L<element objects|HTML::Object::Element> and this will replace the elements children at offset position C<offset> and for a C<length> number of items by the list of objects supplied.
2277  
2278 If consecutive L<text element|HTML::Object::Text> or L<space element|HTML::Object::Space> are provided they will be merged with their immediate previous sibling of the same type.
2279  
2280 For example:
2281  
2282 $e->splice_content( 3, 2, $elem1, $elem2, HTML::Object::Text->new( value => 'Hello world' ) );
2283  
2284 It returns an error if the C<offset> or C<length> provided is not a valid integer.
2285  
2286 Upon success, it returns the current object for chaining.
2287  
2288 =head2 tag
2289  
2290 Returns the tag name of the current element as a L<scalar object|Module::Generic::Scalar>. Be careful at any change you would make as it would directly change the element tag name.
2291  
2292 Non-element tag, such as L<text|HTML::Object::Text> or L<space|HTML::Object::Space> have a pseudo tag starting with an underscore ("_"), such as C<_text> and C<_space>
2293  
2294 =head2 traverse
2295  
2296 Provided with a reference to an existing subroutine, or an anonymous one, and this will crawl through every element of the descending hierarchy and call the callback code, passing it the element object being evaluated. The local variable C<$_> is also made available and set to the element being evaluated.
2297  
2298 =head2 unshift_content
2299  
2300 This acts like L</push_content>, except that instead of appending the elements, this prepends the given element on top of the element children.
2301  
2302 It returns the current element.
2303  
2304 =head1 AUTHOR
2305  
2306 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
2307  
2308 =head1 SEE ALSO
2309  
2310 L<HTML::Object>, L<HTML::Object::Attribute>, L<HTML::Object::Boolean>, L<HTML::Object::Closing>, L<HTML::Object::Collection>, L<HTML::Object::Comment>, L<HTML::Object::Declaration>, L<HTML::Object::Document>, L<HTML::Object::Element>, L<HTML::Object::Exception>, L<HTML::Object::Literal>, L<HTML::Object::Number>, L<HTML::Object::Root>, L<HTML::Object::Space>, L<HTML::Object::Text>, L<HTML::Object::XQuery>
2311  
2312 L<Mozilla Element documentation|https://developer.mozilla.org/en-US/docs/Web/API/Element>
2313  
2314 =head1 COPYRIGHT & LICENSE
2315  
2316 Copyright (c) 2021 DEGUEST Pte. Ltd.
2317  
2318 All rights reserved
2319  
2320 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
2321  
2322 =cut