7 '@{}' => sub { shift->child_nodes },
8 '%{}' => sub { shift->attr },
10 '""' => sub { shift->to_string },
14 use DOM::Tiny::_Collection;
17 use Scalar::Util qw(blessed weaken);
19 our $VERSION = '0.001';
23 my $self = bless \DOM::Tiny::_HTML->new, ref $class || $class;
24 return @_ ? $self->parse(@_) : $self;
27 sub TO_JSON { shift->_delegate('render') }
29 sub all_text { shift->_all_text(1, @_) }
31 sub ancestors { _select($_[0]->_collect($_[0]->_ancestors), $_[1]) }
33 sub append { shift->_add(1, @_) }
34 sub append_content { shift->_content(1, 0, @_) }
38 return undef unless my $result = $self->_css->select_one(@_);
39 return $self->_build($result, $self->xml);
46 my $tree = $self->tree;
47 my $attrs = $tree->[0] ne 'tag' ? {} : $tree->[2];
48 return $attrs unless @_;
51 return $attrs->{$_[0]} unless @_ > 1 || ref $_[0];
54 my $values = ref $_[0] ? $_[0] : {@_};
55 @$attrs{keys %$values} = values %$values;
60 sub child_nodes { $_[0]->_collect(_nodes($_[0]->tree)) }
62 sub children { _select($_[0]->_collect(_nodes($_[0]->tree, 1)), $_[1]) }
67 my $type = $self->type;
68 if ($type eq 'root' || $type eq 'tag') {
69 return $self->_content(0, 1, @_) if @_;
70 my $html = DOM::Tiny::_HTML->new(xml => $self->xml);
71 return join '', map { $html->tree($_)->render } _nodes($self->tree);
74 return $self->tree->[1] unless @_;
75 $self->tree->[1] = shift;
79 sub descendant_nodes { $_[0]->_collect(_all(_nodes($_[0]->tree))) }
81 sub find { $_[0]->_collect(@{$_[0]->_css->select($_[1])}) }
83 sub following { _select($_[0]->_collect(@{$_[0]->_siblings(1)->[1]}), $_[1]) }
84 sub following_nodes { $_[0]->_collect(@{$_[0]->_siblings->[1]}) }
86 sub matches { shift->_css->matches(@_) }
91 return undef if (my $tree = $self->tree)->[0] ne 'tag';
93 # Extract namespace prefix and search parents
94 my $ns = $tree->[1] =~ /^(.*?):/ ? "xmlns:$1" : undef;
95 for my $node ($tree, $self->_ancestors) {
97 # Namespace for prefix
98 my $attrs = $node->[2];
99 if ($ns) { $_ eq $ns and return $attrs->{$_} for keys %$attrs }
101 # Namespace attribute
102 elsif (defined $attrs->{xmlns}) { return $attrs->{xmlns} }
108 sub next { $_[0]->_maybe($_[0]->_siblings(1, 0)->[1]) }
109 sub next_node { $_[0]->_maybe($_[0]->_siblings(0, 0)->[1]) }
113 return undef if $self->tree->[0] eq 'root';
114 return $self->_build($self->_parent, $self->xml);
117 sub parse { shift->_delegate(parse => @_) }
119 sub preceding { _select($_[0]->_collect(@{$_[0]->_siblings(1)->[0]}), $_[1]) }
120 sub preceding_nodes { $_[0]->_collect(@{$_[0]->_siblings->[0]}) }
122 sub prepend { shift->_add(0, @_) }
123 sub prepend_content { shift->_content(0, 0, @_) }
125 sub previous { $_[0]->_maybe($_[0]->_siblings(1, -1)->[0]) }
126 sub previous_node { $_[0]->_maybe($_[0]->_siblings(0, -1)->[0]) }
128 sub remove { shift->replace('') }
131 my ($self, $new) = @_;
132 return $self->parse($new) if (my $tree = $self->tree)->[0] eq 'root';
133 return $self->_replace($self->_parent, $tree, _nodes($self->_parse($new)));
138 return $self unless my $tree = $self->_ancestors(1);
139 return $self->_build($tree, $self->xml);
144 return $self if (my $tree = $self->tree)->[0] ne 'tag';
145 return $self->_replace($tree->[3], $tree, _nodes($tree));
149 my ($self, $tag) = @_;
150 return undef if (my $tree = $self->tree)->[0] ne 'tag';
151 return $tree->[1] unless $tag;
156 sub tap { shift->DOM::Tiny::_Collection::tap(@_) }
158 sub text { shift->_all_text(0, @_) }
160 sub to_string { shift->_delegate('render') }
162 sub tree { shift->_delegate(tree => @_) }
164 sub type { shift->tree->[0] }
170 return $self->{value} // $self->text if (my $tag = $self->tag) eq 'option';
172 # "textarea", "input" or "button"
173 return $tag eq 'textarea' ? $self->text : $self->{value} if $tag ne 'select';
176 my $v = $self->find('option:checked')->map('val');
177 return exists $self->{multiple} ? $v->size ? $v->to_array : undef : $v->last;
180 sub wrap { shift->_wrap(0, @_) }
181 sub wrap_content { shift->_wrap(1, @_) }
183 sub xml { shift->_delegate(xml => @_) }
186 my ($self, $offset, $new) = @_;
188 return $self if (my $tree = $self->tree)->[0] eq 'root';
190 my $parent = $self->_parent;
191 splice @$parent, _offset($parent, $tree) + $offset, 0,
192 _link($parent, _nodes($self->_parse($new)));
198 map { $_->[0] eq 'tag' ? ($_, _all(_nodes($_))) : ($_) } @_;
202 my ($self, $recurse, $trim) = @_;
205 my $tree = $self->tree;
206 $trim = 1 unless defined $trim;
207 map { $_->[1] eq 'pre' and $trim = 0 } $self->_ancestors, $tree
208 if $trim && $tree->[0] ne 'root';
210 return _text([_nodes($tree)], $recurse, $trim);
214 my ($self, $root) = @_;
216 return unless my $tree = $self->_parent;
218 do { push @ancestors, $tree }
219 while ($tree->[0] eq 'tag') && ($tree = $tree->[3]);
220 return $root ? $ancestors[-1] : @ancestors[0 .. $#ancestors - 1];
223 sub _build { shift->new->tree(shift)->xml(shift) }
227 my $xml = $self->xml;
228 return DOM::Tiny::_Collection->new(map { $self->_build($_, $xml) } @_);
232 my ($self, $start, $offset, $new) = @_;
234 my $tree = $self->tree;
235 unless ($tree->[0] eq 'root' || $tree->[0] eq 'tag') {
236 my $old = $self->content;
237 return $self->content($start ? "$old$new" : "$new$old");
240 $start = $start ? ($#$tree + 1) : _start($tree);
241 $offset = $offset ? $#$tree : 0;
242 splice @$tree, $start, $offset, _link($tree, _nodes($self->_parse($new)));
247 sub _css { DOM::Tiny::_CSS->new(tree => shift->tree) }
250 my ($self, $method) = (shift, shift);
251 return $$self->$method unless @_;
257 my ($parent, @children) = @_;
259 # Link parent to children
260 for my $node (@children) {
261 my $offset = $node->[0] eq 'tag' ? 3 : 2;
262 $node->[$offset] = $parent;
263 weaken $node->[$offset];
269 sub _maybe { $_[1] ? $_[0]->_build($_[1], $_[0]->xml) : undef }
272 return unless my $tree = shift;
273 my @nodes = @$tree[_start($tree) .. $#$tree];
274 return shift() ? grep { $_->[0] eq 'tag' } @nodes : @nodes;
278 my ($parent, $child) = @_;
279 my $i = _start($parent);
280 $_ eq $child ? last : $i++ for @$parent[$i .. $#$parent];
284 sub _parent { $_[0]->tree->[$_[0]->type eq 'tag' ? 3 : 2] }
286 sub _parse { DOM::Tiny::_HTML->new(xml => shift->xml)->parse(shift)->tree }
289 my ($self, $parent, $child, @nodes) = @_;
290 splice @$parent, _offset($parent, $child), 1, _link($parent, @nodes);
291 return $self->parent;
295 my ($collection, $selector) = @_;
296 return $collection unless $selector;
297 return $collection->new(grep { $_->matches($selector) } @$collection);
301 my ($self, $tags, $i) = @_;
303 return [] unless my $parent = $self->parent;
305 my $tree = $self->tree;
306 my (@before, @after, $match);
307 for my $node (_nodes($parent->tree)) {
308 ++$match and next if !$match && $node eq $tree;
309 next if $tags && $node->[0] ne 'tag';
310 $match ? push @after, $node : push @before, $node;
313 return defined $i ? [$before[$i], $after[$i]] : [\@before, \@after];
324 sub _start { $_[0][0] eq 'root' ? 1 : 4 }
327 my ($nodes, $recurse, $trim) = @_;
329 # Merge successive text nodes
331 while (my $next = $nodes->[$i + 1]) {
332 ++$i and next unless $nodes->[$i][0] eq 'text' && $next->[0] eq 'text';
333 splice @$nodes, $i, 2, ['text', $nodes->[$i][1] . $next->[1]];
337 for my $node (@$nodes) {
338 my $type = $node->[0];
342 if ($type eq 'text') { $chunk = $trim ? _squish $node->[1] : $node->[1] }
345 elsif ($type eq 'cdata' || $type eq 'raw') { $chunk = $node->[1] }
348 elsif ($type eq 'tag' && $recurse) {
349 no warnings 'recursion';
350 $chunk = _text([_nodes($node)], 1, $node->[1] eq 'pre' ? 0 : $trim);
353 # Add leading whitespace if punctuation allows it
354 $chunk = " $chunk" if $text =~ /\S\z/ && $chunk =~ /^[^.!?,;:\s]+/;
356 # Trim whitespace blocks
357 $text .= $chunk if $chunk =~ /\S+/ || !$trim;
364 my ($self, $content, $new) = @_;
366 $content = 1 if (my $tree = $self->tree)->[0] eq 'root';
367 $content = 0 if $tree->[0] ne 'root' && $tree->[0] ne 'tag';
371 my $first = $new = $self->_parse($new);
372 $current = $first while $first = (_nodes($first, 1))[0];
373 return $self unless $current;
377 push @$current, _link($current, _nodes($tree));
378 splice @$tree, _start($tree), $#$tree, _link($tree, _nodes($new));
383 $self->_replace($self->_parent, $tree, _nodes($new));
384 push @$current, _link($current, $tree);
394 DOM::Tiny - Minimalistic HTML/XML DOM parser with CSS selectors
401 my $dom = DOM::Tiny->new('<div><p id="a">Test</p><p id="b">123</p></div>');
404 say $dom->at('#b')->text;
405 say $dom->find('p')->map('text')->join("\n");
406 say $dom->find('[id]')->map(attr => 'id')->join("\n");
409 $dom->find('p[id]')->reverse->each(sub { say $_->{id} });
412 for my $e ($dom->find('p[id]')->each) {
413 say $e->{id}, ':', $e->text;
417 $dom->find('div p')->last->append('<p id="c">456</p>');
418 $dom->find(':not(p)')->map('strip');
425 L<DOM::Tiny> is a minimalistic and relaxed pure-perl HTML/XML DOM parser based
426 on L<Mojo::DOM>. It supports the L<HTML Living Standard|https://html.spec.whatwg.org/>
427 and L<Extensible Markup Language (XML) 1.0|http://www.w3.org/TR/xml/>, and
428 matching based on L<CSS3 selectors|http://www.w3.org/TR/selectors/>. It will
429 even try to interpret broken HTML and XML, so you should not use it for
432 =head1 NODES AND ELEMENTS
434 When we parse an HTML/XML fragment, it gets turned into a tree of nodes.
438 <head><title>Hello</title></head>
442 There are currently eight different kinds of nodes, C<cdata>, C<comment>,
443 C<doctype>, C<pi>, C<raw>, C<root>, C<tag> and C<text>. Elements are nodes of
455 While all node types are represented as L<DOM::Tiny> objects, some methods like
456 L</"attr"> and L</"namespace"> only apply to elements.
458 =head1 CASE-SENSITIVITY
460 L<DOM::Tiny> defaults to HTML semantics, that means all tags and attribute
461 names are lowercased and selectors need to be lowercase as well.
464 my $dom = DOM::Tiny->new('<P ID="greeting">Hi!</P>');
465 say $dom->at('p[id]')->text;
467 If XML processing instructions are found, the parser will automatically switch
468 into XML mode and everything becomes case-sensitive.
471 my $dom = DOM::Tiny->new('<?xml version="1.0"?><P ID="greeting">Hi!</P>');
472 say $dom->at('P[ID]')->text;
474 XML detection can also be disabled with the L</"xml"> method.
476 # Force XML semantics
477 my $dom = DOM::Tiny->new->xml(1)->parse('<P ID="greeting">Hi!</P>');
478 say $dom->at('P[ID]')->text;
480 # Force HTML semantics
481 my $dom = DOM::Tiny->new->xml(0)->parse('<P ID="greeting">Hi!</P>');
482 say $dom->at('p[id]')->text;
486 L<DOM::Tiny> overloads the following operators.
492 Alias for L</"child_nodes">.
495 $dom->parse('<!-- Test --><b>123</b>')->[0];
507 Alias for L</"attr">.
510 $dom->parse('<div id="test">Test</div>')->at('div')->{id};
516 Alias for L</"to_string">.
520 L<DOM::Tiny> implements the following methods.
524 my $dom = DOM::Tiny->new;
525 my $dom = DOM::Tiny->new('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
527 Construct a new scalar-based L<DOM::Tiny> object and L</"parse"> HTML/XML
528 fragment if necessary.
532 my $trimmed = $dom->all_text;
533 my $untrimmed = $dom->all_text(0);
535 Extract text content from all descendant nodes of this element, smart
536 whitespace trimming is enabled by default.
539 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text;
542 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text(0);
546 my $collection = $dom->ancestors;
547 my $collection = $dom->ancestors('div ~ p');
549 Find all ancestor elements of this node matching the CSS selector and return a
550 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
551 objects. All selectors listed in L</"SELECTORS"> are supported.
553 # List tag names of ancestor elements
554 say $dom->ancestors->map('tag')->join("\n");
558 $dom = $dom->append('<p>I ♥ DOM::Tiny!</p>');
560 Append HTML/XML fragment to this node.
562 # "<div><h1>Test</h1><h2>123</h2></div>"
563 $dom->parse('<div><h1>Test</h1></div>')
564 ->at('h1')->append('<h2>123</h2>')->root;
567 $dom->parse('<p>Test</p>')->at('p')
568 ->child_nodes->first->append(' 123')->root;
570 =head2 append_content
572 $dom = $dom->append_content('<p>I ♥ DOM::Tiny!</p>');
574 Append HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
577 # "<div><h1>Test123</h1></div>"
578 $dom->parse('<div><h1>Test</h1></div>')
579 ->at('h1')->append_content('123')->root;
581 # "<!-- Test 123 --><br>"
582 $dom->parse('<!-- Test --><br>')
583 ->child_nodes->first->append_content('123 ')->root;
585 # "<p>Test<i>123</i></p>"
586 $dom->parse('<p>Test</p>')->at('p')->append_content('<i>123</i>')->root;
590 my $result = $dom->at('div ~ p');
592 Find first descendant element of this element matching the CSS selector and
593 return it as a L<DOM::Tiny> object or return C<undef> if none could be found.
594 All selectors listed in L</"SELECTORS"> are supported.
596 # Find first element with "svg" namespace definition
597 my $namespace = $dom->at('[xmlns\:svg]')->{'xmlns:svg'};
601 my $hash = $dom->attr;
602 my $foo = $dom->attr('foo');
603 $dom = $dom->attr({foo => 'bar'});
604 $dom = $dom->attr(foo => 'bar');
606 This element's attributes.
608 # Remove an attribute
609 delete $dom->attr->{id};
611 # Attribute without value
612 $dom->attr(selected => undef);
615 say $dom->find('*')->map(attr => 'id')->compact->join("\n");
619 my $collection = $dom->child_nodes;
621 Return a L<collection|/"COLLECTION METHODS"> containing all child nodes of this
622 element as L<DOM::Tiny> objects.
624 # "<p><b>123</b></p>"
625 $dom->parse('<p>Test<b>123</b></p>')->at('p')->child_nodes->first->remove;
628 $dom->parse('<!DOCTYPE html><b>123</b>')->child_nodes->first;
631 $dom->parse('<b>123</b><!-- Test -->')->child_nodes->last->content;
635 my $collection = $dom->children;
636 my $collection = $dom->children('div ~ p');
638 Find all child elements of this element matching the CSS selector and return a
639 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
640 objects. All selectors listed in L</"SELECTORS"> are supported.
642 # Show tag name of random child element
643 say $dom->children->shuffle->first->tag;
647 my $str = $dom->content;
648 $dom = $dom->content('<p>I ♥ DOM::Tiny!</p>');
650 Return this node's content or replace it with HTML/XML fragment (for C<root>
651 and C<tag> nodes) or raw content.
654 $dom->parse('<div><b>Test</b></div>')->at('div')->content;
656 # "<div><h1>123</h1></div>"
657 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('123')->root;
659 # "<p><i>123</i></p>"
660 $dom->parse('<p>Test</p>')->at('p')->content('<i>123</i>')->root;
662 # "<div><h1></h1></div>"
663 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('')->root;
666 $dom->parse('<!-- Test --><br>')->child_nodes->first->content;
668 # "<div><!-- 123 -->456</div>"
669 $dom->parse('<div><!-- Test -->456</div>')
670 ->at('div')->child_nodes->first->content(' 123 ')->root;
672 =head2 descendant_nodes
674 my $collection = $dom->descendant_nodes;
676 Return a L<collection|/"COLLECTION METHODS"> containing all descendant nodes of
677 this element as L<DOM::Tiny> objects.
679 # "<p><b>123</b></p>"
680 $dom->parse('<p><!-- Test --><b>123<!-- 456 --></b></p>')
681 ->descendant_nodes->grep(sub { $_->type eq 'comment' })
682 ->map('remove')->first;
684 # "<p><b>test</b>test</p>"
685 $dom->parse('<p><b>123</b>456</p>')
686 ->at('p')->descendant_nodes->grep(sub { $_->type eq 'text' })
687 ->map(content => 'test')->first->root;
691 my $collection = $dom->find('div ~ p');
693 Find all descendant elements of this element matching the CSS selector and
694 return a L<collection|/"COLLECTION METHODS"> containing these elements as
695 L<DOM::Tiny> objects. All selectors listed in L</"SELECTORS"> are supported.
697 # Find a specific element and extract information
698 my $id = $dom->find('div')->[23]{id};
700 # Extract information from multiple elements
701 my @headers = $dom->find('h1, h2, h3')->map('text')->each;
703 # Count all the different tags
704 my $hash = $dom->find('*')->reduce(sub { $a->{$b->tag}++; $a }, {});
706 # Find elements with a class that contains dots
707 my @divs = $dom->find('div.foo\.bar')->each;
711 my $collection = $dom->following;
712 my $collection = $dom->following('div ~ p');
714 Find all sibling elements after this node matching the CSS selector and return
715 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
716 objects. All selectors listen in L</"SELECTORS"> are supported.
718 # List tags of sibling elements after this node
719 say $dom->following->map('tag')->join("\n");
721 =head2 following_nodes
723 my $collection = $dom->following_nodes;
725 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes after
726 this node as L<DOM::Tiny> objects.
729 $dom->parse('<p>A</p><!-- B -->C')->at('p')->following_nodes->last->content;
733 my $bool = $dom->matches('div ~ p');
735 Check if this element matches the CSS selector. All selectors listed in
736 L</"SELECTORS"> are supported.
739 $dom->parse('<p class="a">A</p>')->at('p')->matches('.a');
740 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[class]');
743 $dom->parse('<p class="a">A</p>')->at('p')->matches('.b');
744 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[id]');
748 my $namespace = $dom->namespace;
750 Find this element's namespace or return C<undef> if none could be found.
752 # Find namespace for an element with namespace prefix
753 my $namespace = $dom->at('svg > svg\:circle')->namespace;
755 # Find namespace for an element that may or may not have a namespace prefix
756 my $namespace = $dom->at('svg > circle')->namespace;
760 my $sibling = $dom->next;
762 Return L<DOM::Tiny> object for next sibling element or C<undef> if there are no
766 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h1')->next;
770 my $sibling = $dom->next_node;
772 Return L<DOM::Tiny> object for next sibling node or C<undef> if there are no
776 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
777 ->at('b')->next_node->next_node;
780 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
781 ->at('b')->next_node->content;
785 my $parent = $dom->parent;
787 Return L<DOM::Tiny> object for parent of this node or C<undef> if this node has
792 $dom = $dom->parse('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
794 Parse HTML/XML fragment.
797 my $dom = DOM::Tiny->new->xml(1)->parse($xml);
801 my $collection = $dom->preceding;
802 my $collection = $dom->preceding('div ~ p');
804 Find all sibling elements before this node matching the CSS selector and return
805 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
806 objects. All selectors listed in L</"SELECTORS"> are supported.
808 # List tags of sibling elements before this node
809 say $dom->preceding->map('tag')->join("\n");
811 =head2 preceding_nodes
813 my $collection = $dom->preceding_nodes;
815 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes
816 before this node as L<DOM::Tiny> objects.
819 $dom->parse('A<!-- B --><p>C</p>')->at('p')->preceding_nodes->first->content;
823 $dom = $dom->prepend('<p>I ♥ DOM::Tiny!</p>');
825 Prepend HTML/XML fragment to this node.
827 # "<div><h1>Test</h1><h2>123</h2></div>"
828 $dom->parse('<div><h2>123</h2></div>')
829 ->at('h2')->prepend('<h1>Test</h1>')->root;
832 $dom->parse('<p>123</p>')
833 ->at('p')->child_nodes->first->prepend('Test ')->root;
835 =head2 prepend_content
837 $dom = $dom->prepend_content('<p>I ♥ DOM::Tiny!</p>');
839 Prepend HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
842 # "<div><h2>Test123</h2></div>"
843 $dom->parse('<div><h2>123</h2></div>')
844 ->at('h2')->prepend_content('Test')->root;
846 # "<!-- Test 123 --><br>"
847 $dom->parse('<!-- 123 --><br>')
848 ->child_nodes->first->prepend_content(' Test')->root;
850 # "<p><i>123</i>Test</p>"
851 $dom->parse('<p>Test</p>')->at('p')->prepend_content('<i>123</i>')->root;
855 my $sibling = $dom->previous;
857 Return L<DOM::Tiny> object for previous sibling element or C<undef> if there
858 are no more siblings.
861 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h2')->previous;
865 my $sibling = $dom->previous_node;
867 Return L<DOM::Tiny> object for previous sibling node or C<undef> if there are
871 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
872 ->at('b')->previous_node->previous_node;
875 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
876 ->at('b')->previous_node->content;
880 my $parent = $dom->remove;
882 Remove this node and return L</"root"> (for C<root> nodes) or L</"parent">.
885 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->remove;
887 # "<p><b>456</b></p>"
888 $dom->parse('<p>123<b>456</b></p>')
889 ->at('p')->child_nodes->first->remove->root;
893 my $parent = $dom->replace('<div>I ♥ DOM::Tiny!</div>');
895 Replace this node with HTML/XML fragment and return L</"root"> (for C<root>
896 nodes) or L</"parent">.
898 # "<div><h2>123</h2></div>"
899 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->replace('<h2>123</h2>');
901 # "<p><b>123</b></p>"
902 $dom->parse('<p>Test</p>')
903 ->at('p')->child_nodes->[0]->replace('<b>123</b>')->root;
907 my $root = $dom->root;
909 Return L<DOM::Tiny> object for C<root> node.
913 my $parent = $dom->strip;
915 Remove this element while preserving its content and return L</"parent">.
918 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->strip;
923 $dom = $dom->tag('div');
925 This element's tag name.
927 # List tag names of child elements
928 say $dom->children->map('tag')->join("\n");
932 $dom = $dom->tap(sub {...});
934 Equivalent to L<Mojo::Base/"tap">.
938 my $trimmed = $dom->text;
939 my $untrimmed = $dom->text(0);
941 Extract text content from this element only (not including child elements),
942 smart whitespace trimming is enabled by default.
945 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text;
948 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text(0);
952 my $str = $dom->to_string;
954 Render this node and its content to HTML/XML.
957 $dom->parse('<div><b>Test</b></div>')->at('div b')->to_string;
961 my $tree = $dom->tree;
962 $dom = $dom->tree(['root']);
964 Document Object Model. Note that this structure should only be used very
965 carefully since it is very dynamic.
969 my $type = $dom->type;
971 This node's type, usually C<cdata>, C<comment>, C<doctype>, C<pi>, C<raw>,
972 C<root>, C<tag> or C<text>.
975 $dom->parse('<![CDATA[Test]]>')->child_nodes->first->type;
978 $dom->parse('<!-- Test -->')->child_nodes->first->type;
981 $dom->parse('<!DOCTYPE html>')->child_nodes->first->type;
984 $dom->parse('<?xml version="1.0"?>')->child_nodes->first->type;
987 $dom->parse('<title>Test</title>')->at('title')->child_nodes->first->type;
990 $dom->parse('<p>Test</p>')->type;
993 $dom->parse('<p>Test</p>')->at('p')->type;
996 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->type;
1000 my $value = $dom->val;
1002 Extract value from form element (such as C<button>, C<input>, C<option>,
1003 C<select> and C<textarea>) or return C<undef> if this element has no value. In
1004 the case of C<select> with C<multiple> attribute, find C<option> elements with
1005 C<selected> attribute and return an array reference with all values or C<undef>
1006 if none could be found.
1009 $dom->parse('<input name="test" value="a">')->at('input')->val;
1012 $dom->parse('<textarea>b</textarea>')->at('textarea')->val;
1015 $dom->parse('<option value="c">Test</option>')->at('option')->val;
1018 $dom->parse('<select><option selected>d</option></select>')
1019 ->at('select')->val;
1022 $dom->parse('<select multiple><option selected>e</option></select>')
1023 ->at('select')->val->[0];
1027 $dom = $dom->wrap('<div></div>');
1029 Wrap HTML/XML fragment around this node, placing it as the last child of the
1030 first innermost element.
1032 # "<p>123<b>Test</b></p>"
1033 $dom->parse('<b>Test</b>')->at('b')->wrap('<p>123</p>')->root;
1035 # "<div><p><b>Test</b></p>123</div>"
1036 $dom->parse('<b>Test</b>')->at('b')->wrap('<div><p></p>123</div>')->root;
1038 # "<p><b>Test</b></p><p>123</p>"
1039 $dom->parse('<b>Test</b>')->at('b')->wrap('<p></p><p>123</p>')->root;
1041 # "<p><b>Test</b></p>"
1042 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->wrap('<b>')->root;
1046 $dom = $dom->wrap_content('<div></div>');
1048 Wrap HTML/XML fragment around this node's content, placing it as the last
1049 children of the first innermost element.
1051 # "<p><b>123Test</b></p>"
1052 $dom->parse('<p>Test<p>')->at('p')->wrap_content('<b>123</b>')->root;
1054 # "<p><b>Test</b></p><p>123</p>"
1055 $dom->parse('<b>Test</b>')->wrap_content('<p></p><p>123</p>');
1059 my $bool = $dom->xml;
1060 $dom = $dom->xml($bool);
1062 Disable HTML semantics in parser and activate case-sensitivity, defaults to
1063 auto detection based on processing instructions.
1065 =head1 COLLECTION METHODS
1067 Some L<DOM::Tiny> methods return an array-based collection object based on
1068 L<Mojo::Collection>, which can either be accessed directly as an array
1069 reference, or with the following methods.
1072 $collection->map(sub { ucfirst })->shuffle->each(sub {
1073 my ($word, $num) = @_;
1077 # Access array directly to manipulate collection
1078 $collection->[23] += 100;
1079 say for @$collection;
1083 my $new = $collection->compact;
1085 Create a new collection with all elements that are defined and not an empty
1088 # $collection contains (0, 1, undef, 2, '', 3)
1089 $collection->compact->join(', '); # "0, 1, 2, 3"
1093 my @elements = $collection->each;
1094 $collection = $collection->each(sub {...});
1096 Evaluate callback for each element in collection or return all elements as a
1097 list if none has been provided. The element will be the first argument passed
1098 to the callback and is also available as C<$_>.
1100 # Make a numbered list
1101 $collection->each(sub {
1108 my $first = $collection->first;
1109 my $first = $collection->first(qr/foo/);
1110 my $first = $collection->first(sub {...});
1111 my $first = $collection->first($method);
1112 my $first = $collection->first($method, @args);
1114 Evaluate regular expression/callback for, or call method on, each element in
1115 collection and return the first one that matched the regular expression, or for
1116 which the callback/method returned true. The element will be the first argument
1117 passed to the callback and is also available as C<$_>.
1120 my $first = $collection->first(sub { $_->$method(@args) });
1122 # Find first value that contains the word "dom"
1123 my $interesting = $collection->first(qr/dom/i);
1125 # Find first value that is greater than 5
1126 my $greater = $collection->first(sub { $_ > 5 });
1130 my $new = $collection->flatten;
1132 Flatten nested collections/arrays recursively and create a new collection with
1135 # $collection contains (1, [2, [3, 4], 5, [6]], 7)
1136 $collection->flatten->join(', '); # "1, 2, 3, 4, 5, 6, 7"
1140 my $new = $collection->grep(qr/foo/);
1141 my $new = $collection->grep(sub {...});
1142 my $new = $collection->grep($method);
1143 my $new = $collection->grep($method, @args);
1145 Evaluate regular expression/callback for, or call method on, each element in
1146 collection and create a new collection with all elements that matched the
1147 regular expression, or for which the callback/method returned true. The element
1148 will be the first argument passed to the callback and is also available as
1152 my $new = $collection->grep(sub { $_->$method(@args) });
1154 # Find all values that contain the word "dom"
1155 my $interesting = $collection->grep(qr/dom/i);
1157 # Find all values that are greater than 5
1158 my $greater = $collection->grep(sub { $_ > 5 });
1162 my $stream = $collection->join;
1163 my $stream = $collection->join("\n");
1165 Turn collection into string.
1167 # Join all values with commas
1168 $collection->join(', ');
1172 my $last = $collection->last;
1174 Return the last element in collection.
1178 my $new = $collection->map(sub {...});
1179 my $new = $collection->map($method);
1180 my $new = $collection->map($method, @args);
1182 Evaluate callback for, or call method on, each element in collection and create
1183 a new collection from the results. The element will be the first argument
1184 passed to the callback and is also available as C<$_>.
1187 my $new = $collection->map(sub { $_->$method(@args) });
1189 # Append the word "dom" to all values
1190 my $domified = $collection->map(sub { $_ . 'dom' });
1194 my $result = $collection->reduce(sub {...});
1195 my $result = $collection->reduce(sub {...}, $initial);
1197 Reduce elements in collection with callback, the first element will be used as
1198 initial value if none has been provided.
1200 # Calculate the sum of all values
1201 my $sum = $collection->reduce(sub { $a + $b });
1203 # Count how often each value occurs in collection
1204 my $hash = $collection->reduce(sub { $a->{$b}++; $a }, {});
1208 my $new = $collection->reverse;
1210 Create a new collection with all elements in reverse order.
1214 my $new = $collection->slice(4 .. 7);
1216 Create a new collection with all selected elements.
1218 # $collection contains ('A', 'B', 'C', 'D', 'E')
1219 $collection->slice(1, 2, 4)->join(' '); # "B C E"
1223 my $new = $collection->shuffle;
1225 Create a new collection with all elements in random order.
1229 my $size = $collection->size;
1231 Number of elements in collection.
1235 my $new = $collection->sort;
1236 my $new = $collection->sort(sub {...});
1238 Sort elements based on return value of callback and create a new collection
1241 # Sort values case-insensitive
1242 my $case_insensitive = $collection->sort(sub { uc($a) cmp uc($b) });
1246 $collection = $collection->tap(sub {...});
1248 Equivalent to L<Mojo::Base/"tap">.
1252 my $array = $collection->to_array;
1254 Turn collection into array reference.
1258 my $new = $collection->uniq;
1259 my $new = $collection->uniq(sub {...});
1260 my $new = $collection->uniq($method);
1261 my $new = $collection->uniq($method, @args);
1263 Create a new collection without duplicate elements, using the string
1264 representation of either the elements or the return value of the
1268 my $new = $collection->uniq(sub { $_->$method(@args) });
1270 # $collection contains ('foo', 'bar', 'bar', 'baz')
1271 $collection->uniq->join(' '); # "foo bar baz"
1273 # $collection contains ([1, 2], [2, 1], [3, 2])
1274 $collection->uniq(sub{ $_->[1] })->to_array; # "[[1, 2], [2, 1]]"
1278 L<DOM::Tiny> uses a CSS selector engine based on L<Mojo::DOM::CSS>. All CSS
1279 selectors that make sense for a standalone parser are supported.
1285 my $all = $dom->find('*');
1289 An element of type C<E>.
1291 my $title = $dom->at('title');
1295 An C<E> element with a C<foo> attribute.
1297 my $links = $dom->find('a[href]');
1301 An C<E> element whose C<foo> attribute value is exactly equal to C<bar>.
1303 my $case_sensitive = $dom->find('input[type="hidden"]');
1304 my $case_sensitive = $dom->find('input[type=hidden]');
1306 =head2 E[foo="bar" i]
1308 An C<E> element whose C<foo> attribute value is exactly equal to any
1309 (ASCII-range) case-permutation of C<bar>. Note that this selector is
1310 EXPERIMENTAL and might change without warning!
1312 my $case_insensitive = $dom->find('input[type="hidden" i]');
1313 my $case_insensitive = $dom->find('input[type=hidden i]');
1314 my $case_insensitive = $dom->find('input[class~="foo" i]');
1316 This selector is part of
1317 L<Selectors Level 4|http://dev.w3.org/csswg/selectors-4>, which is still a work
1320 =head2 E[foo~="bar"]
1322 An C<E> element whose C<foo> attribute value is a list of whitespace-separated
1323 values, one of which is exactly equal to C<bar>.
1325 my $foo = $dom->find('input[class~="foo"]');
1326 my $foo = $dom->find('input[class~=foo]');
1328 =head2 E[foo^="bar"]
1330 An C<E> element whose C<foo> attribute value begins exactly with the string
1333 my $begins_with = $dom->find('input[name^="f"]');
1334 my $begins_with = $dom->find('input[name^=f]');
1336 =head2 E[foo$="bar"]
1338 An C<E> element whose C<foo> attribute value ends exactly with the string
1341 my $ends_with = $dom->find('input[name$="o"]');
1342 my $ends_with = $dom->find('input[name$=o]');
1344 =head2 E[foo*="bar"]
1346 An C<E> element whose C<foo> attribute value contains the substring C<bar>.
1348 my $contains = $dom->find('input[name*="fo"]');
1349 my $contains = $dom->find('input[name*=fo]');
1353 An C<E> element, root of the document.
1355 my $root = $dom->at(':root');
1357 =head2 E:nth-child(n)
1359 An C<E> element, the C<n-th> child of its parent.
1361 my $third = $dom->find('div:nth-child(3)');
1362 my $odd = $dom->find('div:nth-child(odd)');
1363 my $even = $dom->find('div:nth-child(even)');
1364 my $top3 = $dom->find('div:nth-child(-n+3)');
1366 =head2 E:nth-last-child(n)
1368 An C<E> element, the C<n-th> child of its parent, counting from the last one.
1370 my $third = $dom->find('div:nth-last-child(3)');
1371 my $odd = $dom->find('div:nth-last-child(odd)');
1372 my $even = $dom->find('div:nth-last-child(even)');
1373 my $bottom3 = $dom->find('div:nth-last-child(-n+3)');
1375 =head2 E:nth-of-type(n)
1377 An C<E> element, the C<n-th> sibling of its type.
1379 my $third = $dom->find('div:nth-of-type(3)');
1380 my $odd = $dom->find('div:nth-of-type(odd)');
1381 my $even = $dom->find('div:nth-of-type(even)');
1382 my $top3 = $dom->find('div:nth-of-type(-n+3)');
1384 =head2 E:nth-last-of-type(n)
1386 An C<E> element, the C<n-th> sibling of its type, counting from the last one.
1388 my $third = $dom->find('div:nth-last-of-type(3)');
1389 my $odd = $dom->find('div:nth-last-of-type(odd)');
1390 my $even = $dom->find('div:nth-last-of-type(even)');
1391 my $bottom3 = $dom->find('div:nth-last-of-type(-n+3)');
1393 =head2 E:first-child
1395 An C<E> element, first child of its parent.
1397 my $first = $dom->find('div p:first-child');
1401 An C<E> element, last child of its parent.
1403 my $last = $dom->find('div p:last-child');
1405 =head2 E:first-of-type
1407 An C<E> element, first sibling of its type.
1409 my $first = $dom->find('div p:first-of-type');
1411 =head2 E:last-of-type
1413 An C<E> element, last sibling of its type.
1415 my $last = $dom->find('div p:last-of-type');
1419 An C<E> element, only child of its parent.
1421 my $lonely = $dom->find('div p:only-child');
1423 =head2 E:only-of-type
1425 An C<E> element, only sibling of its type.
1427 my $lonely = $dom->find('div p:only-of-type');
1431 An C<E> element that has no children (including text nodes).
1433 my $empty = $dom->find(':empty');
1437 A user interface element C<E> which is checked (for instance a radio-button or
1440 my $input = $dom->find(':checked');
1444 An C<E> element whose class is "warning".
1446 my $warning = $dom->find('div.warning');
1450 An C<E> element with C<ID> equal to "myid".
1452 my $foo = $dom->at('div#foo');
1456 An C<E> element that does not match simple selector C<s>.
1458 my $others = $dom->find('div p:not(:first-child)');
1462 An C<F> element descendant of an C<E> element.
1464 my $headlines = $dom->find('div h1');
1468 An C<F> element child of an C<E> element.
1470 my $headlines = $dom->find('html > body > div > h1');
1474 An C<F> element immediately preceded by an C<E> element.
1476 my $second = $dom->find('h1 + h2');
1480 An C<F> element preceded by an C<E> element.
1482 my $second = $dom->find('h1 ~ h2');
1486 Elements of type C<E>, C<F> and C<G>.
1488 my $headlines = $dom->find('h1, h2, h3');
1490 =head2 E[foo=bar][bar=baz]
1492 An C<E> element whose attributes match all following attribute selectors.
1494 my $links = $dom->find('a[foo^=b][foo$=ar]');
1498 Report any issues on the public bugtracker.
1502 Dan Book <dbook@cpan.org>
1504 =head1 COPYRIGHT AND LICENSE
1506 This software is Copyright (c) 2015 by Dan Book.
1508 This is free software, licensed under:
1510 The Artistic License 2.0 (GPL Compatible)
1514 L<Mojo::DOM>, L<XML::LibXML>, L<XML::Twig>, L<HTML::TreeBuilder>, L<XML::Smart>
1516 =for Pod::Coverage TO_JSON