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 { 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> uses a CSS selector engine based on L<Mojo::DOM::CSS>. All CSS
487 selectors that make sense for a standalone parser are supported.
493 my $all = $dom->find('*');
497 An element of type C<E>.
499 my $title = $dom->at('title');
503 An C<E> element with a C<foo> attribute.
505 my $links = $dom->find('a[href]');
509 An C<E> element whose C<foo> attribute value is exactly equal to C<bar>.
511 my $case_sensitive = $dom->find('input[type="hidden"]');
512 my $case_sensitive = $dom->find('input[type=hidden]');
514 =head2 E[foo="bar" i]
516 An C<E> element whose C<foo> attribute value is exactly equal to any
517 (ASCII-range) case-permutation of C<bar>. Note that this selector is
518 EXPERIMENTAL and might change without warning!
520 my $case_insensitive = $dom->find('input[type="hidden" i]');
521 my $case_insensitive = $dom->find('input[type=hidden i]');
522 my $case_insensitive = $dom->find('input[class~="foo" i]');
524 This selector is part of
525 L<Selectors Level 4|http://dev.w3.org/csswg/selectors-4>, which is still a work
530 An C<E> element whose C<foo> attribute value is a list of whitespace-separated
531 values, one of which is exactly equal to C<bar>.
533 my $foo = $dom->find('input[class~="foo"]');
534 my $foo = $dom->find('input[class~=foo]');
538 An C<E> element whose C<foo> attribute value begins exactly with the string
541 my $begins_with = $dom->find('input[name^="f"]');
542 my $begins_with = $dom->find('input[name^=f]');
546 An C<E> element whose C<foo> attribute value ends exactly with the string
549 my $ends_with = $dom->find('input[name$="o"]');
550 my $ends_with = $dom->find('input[name$=o]');
554 An C<E> element whose C<foo> attribute value contains the substring C<bar>.
556 my $contains = $dom->find('input[name*="fo"]');
557 my $contains = $dom->find('input[name*=fo]');
561 An C<E> element, root of the document.
563 my $root = $dom->at(':root');
565 =head2 E:nth-child(n)
567 An C<E> element, the C<n-th> child of its parent.
569 my $third = $dom->find('div:nth-child(3)');
570 my $odd = $dom->find('div:nth-child(odd)');
571 my $even = $dom->find('div:nth-child(even)');
572 my $top3 = $dom->find('div:nth-child(-n+3)');
574 =head2 E:nth-last-child(n)
576 An C<E> element, the C<n-th> child of its parent, counting from the last one.
578 my $third = $dom->find('div:nth-last-child(3)');
579 my $odd = $dom->find('div:nth-last-child(odd)');
580 my $even = $dom->find('div:nth-last-child(even)');
581 my $bottom3 = $dom->find('div:nth-last-child(-n+3)');
583 =head2 E:nth-of-type(n)
585 An C<E> element, the C<n-th> sibling of its type.
587 my $third = $dom->find('div:nth-of-type(3)');
588 my $odd = $dom->find('div:nth-of-type(odd)');
589 my $even = $dom->find('div:nth-of-type(even)');
590 my $top3 = $dom->find('div:nth-of-type(-n+3)');
592 =head2 E:nth-last-of-type(n)
594 An C<E> element, the C<n-th> sibling of its type, counting from the last one.
596 my $third = $dom->find('div:nth-last-of-type(3)');
597 my $odd = $dom->find('div:nth-last-of-type(odd)');
598 my $even = $dom->find('div:nth-last-of-type(even)');
599 my $bottom3 = $dom->find('div:nth-last-of-type(-n+3)');
603 An C<E> element, first child of its parent.
605 my $first = $dom->find('div p:first-child');
609 An C<E> element, last child of its parent.
611 my $last = $dom->find('div p:last-child');
613 =head2 E:first-of-type
615 An C<E> element, first sibling of its type.
617 my $first = $dom->find('div p:first-of-type');
619 =head2 E:last-of-type
621 An C<E> element, last sibling of its type.
623 my $last = $dom->find('div p:last-of-type');
627 An C<E> element, only child of its parent.
629 my $lonely = $dom->find('div p:only-child');
631 =head2 E:only-of-type
633 An C<E> element, only sibling of its type.
635 my $lonely = $dom->find('div p:only-of-type');
639 An C<E> element that has no children (including text nodes).
641 my $empty = $dom->find(':empty');
645 A user interface element C<E> which is checked (for instance a radio-button or
648 my $input = $dom->find(':checked');
652 An C<E> element whose class is "warning".
654 my $warning = $dom->find('div.warning');
658 An C<E> element with C<ID> equal to "myid".
660 my $foo = $dom->at('div#foo');
664 An C<E> element that does not match simple selector C<s>.
666 my $others = $dom->find('div p:not(:first-child)');
670 An C<F> element descendant of an C<E> element.
672 my $headlines = $dom->find('div h1');
676 An C<F> element child of an C<E> element.
678 my $headlines = $dom->find('html > body > div > h1');
682 An C<F> element immediately preceded by an C<E> element.
684 my $second = $dom->find('h1 + h2');
688 An C<F> element preceded by an C<E> element.
690 my $second = $dom->find('h1 ~ h2');
694 Elements of type C<E>, C<F> and C<G>.
696 my $headlines = $dom->find('h1, h2, h3');
698 =head2 E[foo=bar][bar=baz]
700 An C<E> element whose attributes match all following attribute selectors.
702 my $links = $dom->find('a[foo^=b][foo$=ar]');
706 L<DOM::Tiny> overloads the following operators.
712 Alias for L</"child_nodes">.
715 $dom->parse('<!-- Test --><b>123</b>')->[0];
727 Alias for L</"attr">.
730 $dom->parse('<div id="test">Test</div>')->at('div')->{id};
736 Alias for L</"to_string">.
740 L<DOM::Tiny> implements the following methods.
744 my $dom = DOM::Tiny->new;
745 my $dom = DOM::Tiny->new('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
747 Construct a new scalar-based L<DOM::Tiny> object and L</"parse"> HTML/XML
748 fragment if necessary.
752 my $trimmed = $dom->all_text;
753 my $untrimmed = $dom->all_text(0);
755 Extract text content from all descendant nodes of this element, smart
756 whitespace trimming is enabled by default.
759 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text;
762 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text(0);
766 my $collection = $dom->ancestors;
767 my $collection = $dom->ancestors('div ~ p');
769 Find all ancestor elements of this node matching the CSS selector and return a
770 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
771 objects. All selectors listed in L</"SELECTORS"> are supported.
773 # List tag names of ancestor elements
774 say $dom->ancestors->map('tag')->join("\n");
778 $dom = $dom->append('<p>I ♥ DOM::Tiny!</p>');
780 Append HTML/XML fragment to this node.
782 # "<div><h1>Test</h1><h2>123</h2></div>"
783 $dom->parse('<div><h1>Test</h1></div>')
784 ->at('h1')->append('<h2>123</h2>')->root;
787 $dom->parse('<p>Test</p>')->at('p')
788 ->child_nodes->first->append(' 123')->root;
790 =head2 append_content
792 $dom = $dom->append_content('<p>I ♥ DOM::Tiny!</p>');
794 Append HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
797 # "<div><h1>Test123</h1></div>"
798 $dom->parse('<div><h1>Test</h1></div>')
799 ->at('h1')->append_content('123')->root;
801 # "<!-- Test 123 --><br>"
802 $dom->parse('<!-- Test --><br>')
803 ->child_nodes->first->append_content('123 ')->root;
805 # "<p>Test<i>123</i></p>"
806 $dom->parse('<p>Test</p>')->at('p')->append_content('<i>123</i>')->root;
810 my $result = $dom->at('div ~ p');
812 Find first descendant element of this element matching the CSS selector and
813 return it as a L<DOM::Tiny> object or return C<undef> if none could be found.
814 All selectors listed in L</"SELECTORS"> are supported.
816 # Find first element with "svg" namespace definition
817 my $namespace = $dom->at('[xmlns\:svg]')->{'xmlns:svg'};
821 my $hash = $dom->attr;
822 my $foo = $dom->attr('foo');
823 $dom = $dom->attr({foo => 'bar'});
824 $dom = $dom->attr(foo => 'bar');
826 This element's attributes.
828 # Remove an attribute
829 delete $dom->attr->{id};
831 # Attribute without value
832 $dom->attr(selected => undef);
835 say $dom->find('*')->map(attr => 'id')->compact->join("\n");
839 my $collection = $dom->child_nodes;
841 Return a L<collection|/"COLLECTION METHODS"> containing all child nodes of this
842 element as L<DOM::Tiny> objects.
844 # "<p><b>123</b></p>"
845 $dom->parse('<p>Test<b>123</b></p>')->at('p')->child_nodes->first->remove;
848 $dom->parse('<!DOCTYPE html><b>123</b>')->child_nodes->first;
851 $dom->parse('<b>123</b><!-- Test -->')->child_nodes->last->content;
855 my $collection = $dom->children;
856 my $collection = $dom->children('div ~ p');
858 Find all child elements of this element matching the CSS selector and return a
859 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
860 objects. All selectors listed in L</"SELECTORS"> are supported.
862 # Show tag name of random child element
863 say $dom->children->shuffle->first->tag;
867 my $str = $dom->content;
868 $dom = $dom->content('<p>I ♥ DOM::Tiny!</p>');
870 Return this node's content or replace it with HTML/XML fragment (for C<root>
871 and C<tag> nodes) or raw content.
874 $dom->parse('<div><b>Test</b></div>')->at('div')->content;
876 # "<div><h1>123</h1></div>"
877 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('123')->root;
879 # "<p><i>123</i></p>"
880 $dom->parse('<p>Test</p>')->at('p')->content('<i>123</i>')->root;
882 # "<div><h1></h1></div>"
883 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('')->root;
886 $dom->parse('<!-- Test --><br>')->child_nodes->first->content;
888 # "<div><!-- 123 -->456</div>"
889 $dom->parse('<div><!-- Test -->456</div>')
890 ->at('div')->child_nodes->first->content(' 123 ')->root;
892 =head2 descendant_nodes
894 my $collection = $dom->descendant_nodes;
896 Return a L<collection|/"COLLECTION METHODS"> containing all descendant nodes of
897 this element as L<DOM::Tiny> objects.
899 # "<p><b>123</b></p>"
900 $dom->parse('<p><!-- Test --><b>123<!-- 456 --></b></p>')
901 ->descendant_nodes->grep(sub { $_->type eq 'comment' })
902 ->map('remove')->first;
904 # "<p><b>test</b>test</p>"
905 $dom->parse('<p><b>123</b>456</p>')
906 ->at('p')->descendant_nodes->grep(sub { $_->type eq 'text' })
907 ->map(content => 'test')->first->root;
911 my $collection = $dom->find('div ~ p');
913 Find all descendant elements of this element matching the CSS selector and
914 return a L<collection|/"COLLECTION METHODS"> containing these elements as
915 L<DOM::Tiny> objects. All selectors listed in L</"SELECTORS"> are supported.
917 # Find a specific element and extract information
918 my $id = $dom->find('div')->[23]{id};
920 # Extract information from multiple elements
921 my @headers = $dom->find('h1, h2, h3')->map('text')->each;
923 # Count all the different tags
924 my $hash = $dom->find('*')->reduce(sub { $a->{$b->tag}++; $a }, {});
926 # Find elements with a class that contains dots
927 my @divs = $dom->find('div.foo\.bar')->each;
931 my $collection = $dom->following;
932 my $collection = $dom->following('div ~ p');
934 Find all sibling elements after this node matching the CSS selector and return
935 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
936 objects. All selectors listen in L</"SELECTORS"> are supported.
938 # List tags of sibling elements after this node
939 say $dom->following->map('tag')->join("\n");
941 =head2 following_nodes
943 my $collection = $dom->following_nodes;
945 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes after
946 this node as L<DOM::Tiny> objects.
949 $dom->parse('<p>A</p><!-- B -->C')->at('p')->following_nodes->last->content;
953 my $bool = $dom->matches('div ~ p');
955 Check if this element matches the CSS selector. All selectors listed in
956 L</"SELECTORS"> are supported.
959 $dom->parse('<p class="a">A</p>')->at('p')->matches('.a');
960 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[class]');
963 $dom->parse('<p class="a">A</p>')->at('p')->matches('.b');
964 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[id]');
968 my $namespace = $dom->namespace;
970 Find this element's namespace or return C<undef> if none could be found.
972 # Find namespace for an element with namespace prefix
973 my $namespace = $dom->at('svg > svg\:circle')->namespace;
975 # Find namespace for an element that may or may not have a namespace prefix
976 my $namespace = $dom->at('svg > circle')->namespace;
980 my $sibling = $dom->next;
982 Return L<DOM::Tiny> object for next sibling element or C<undef> if there are no
986 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h1')->next;
990 my $sibling = $dom->next_node;
992 Return L<DOM::Tiny> object for next sibling node or C<undef> if there are no
996 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
997 ->at('b')->next_node->next_node;
1000 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
1001 ->at('b')->next_node->content;
1005 my $parent = $dom->parent;
1007 Return L<DOM::Tiny> object for parent of this node or C<undef> if this node has
1012 $dom = $dom->parse('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
1014 Parse HTML/XML fragment.
1017 my $dom = DOM::Tiny->new->xml(1)->parse($xml);
1021 my $collection = $dom->preceding;
1022 my $collection = $dom->preceding('div ~ p');
1024 Find all sibling elements before this node matching the CSS selector and return
1025 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
1026 objects. All selectors listed in L</"SELECTORS"> are supported.
1028 # List tags of sibling elements before this node
1029 say $dom->preceding->map('tag')->join("\n");
1031 =head2 preceding_nodes
1033 my $collection = $dom->preceding_nodes;
1035 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes
1036 before this node as L<DOM::Tiny> objects.
1039 $dom->parse('A<!-- B --><p>C</p>')->at('p')->preceding_nodes->first->content;
1043 $dom = $dom->prepend('<p>I ♥ DOM::Tiny!</p>');
1045 Prepend HTML/XML fragment to this node.
1047 # "<div><h1>Test</h1><h2>123</h2></div>"
1048 $dom->parse('<div><h2>123</h2></div>')
1049 ->at('h2')->prepend('<h1>Test</h1>')->root;
1052 $dom->parse('<p>123</p>')
1053 ->at('p')->child_nodes->first->prepend('Test ')->root;
1055 =head2 prepend_content
1057 $dom = $dom->prepend_content('<p>I ♥ DOM::Tiny!</p>');
1059 Prepend HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
1062 # "<div><h2>Test123</h2></div>"
1063 $dom->parse('<div><h2>123</h2></div>')
1064 ->at('h2')->prepend_content('Test')->root;
1066 # "<!-- Test 123 --><br>"
1067 $dom->parse('<!-- 123 --><br>')
1068 ->child_nodes->first->prepend_content(' Test')->root;
1070 # "<p><i>123</i>Test</p>"
1071 $dom->parse('<p>Test</p>')->at('p')->prepend_content('<i>123</i>')->root;
1075 my $sibling = $dom->previous;
1077 Return L<DOM::Tiny> object for previous sibling element or C<undef> if there
1078 are no more siblings.
1081 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h2')->previous;
1083 =head2 previous_node
1085 my $sibling = $dom->previous_node;
1087 Return L<DOM::Tiny> object for previous sibling node or C<undef> if there are
1091 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
1092 ->at('b')->previous_node->previous_node;
1095 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
1096 ->at('b')->previous_node->content;
1100 my $parent = $dom->remove;
1102 Remove this node and return L</"root"> (for C<root> nodes) or L</"parent">.
1105 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->remove;
1107 # "<p><b>456</b></p>"
1108 $dom->parse('<p>123<b>456</b></p>')
1109 ->at('p')->child_nodes->first->remove->root;
1113 my $parent = $dom->replace('<div>I ♥ DOM::Tiny!</div>');
1115 Replace this node with HTML/XML fragment and return L</"root"> (for C<root>
1116 nodes) or L</"parent">.
1118 # "<div><h2>123</h2></div>"
1119 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->replace('<h2>123</h2>');
1121 # "<p><b>123</b></p>"
1122 $dom->parse('<p>Test</p>')
1123 ->at('p')->child_nodes->[0]->replace('<b>123</b>')->root;
1127 my $root = $dom->root;
1129 Return L<DOM::Tiny> object for C<root> node.
1133 my $parent = $dom->strip;
1135 Remove this element while preserving its content and return L</"parent">.
1138 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->strip;
1142 my $tag = $dom->tag;
1143 $dom = $dom->tag('div');
1145 This element's tag name.
1147 # List tag names of child elements
1148 say $dom->children->map('tag')->join("\n");
1152 $dom = $dom->tap(sub {...});
1154 Equivalent to L<Mojo::Base/"tap">.
1158 my $trimmed = $dom->text;
1159 my $untrimmed = $dom->text(0);
1161 Extract text content from this element only (not including child elements),
1162 smart whitespace trimming is enabled by default.
1165 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text;
1168 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text(0);
1172 my $str = $dom->to_string;
1174 Render this node and its content to HTML/XML.
1177 $dom->parse('<div><b>Test</b></div>')->at('div b')->to_string;
1181 my $tree = $dom->tree;
1182 $dom = $dom->tree(['root']);
1184 Document Object Model. Note that this structure should only be used very
1185 carefully since it is very dynamic.
1189 my $type = $dom->type;
1191 This node's type, usually C<cdata>, C<comment>, C<doctype>, C<pi>, C<raw>,
1192 C<root>, C<tag> or C<text>.
1195 $dom->parse('<![CDATA[Test]]>')->child_nodes->first->type;
1198 $dom->parse('<!-- Test -->')->child_nodes->first->type;
1201 $dom->parse('<!DOCTYPE html>')->child_nodes->first->type;
1204 $dom->parse('<?xml version="1.0"?>')->child_nodes->first->type;
1207 $dom->parse('<title>Test</title>')->at('title')->child_nodes->first->type;
1210 $dom->parse('<p>Test</p>')->type;
1213 $dom->parse('<p>Test</p>')->at('p')->type;
1216 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->type;
1220 my $value = $dom->val;
1222 Extract value from form element (such as C<button>, C<input>, C<option>,
1223 C<select> and C<textarea>) or return C<undef> if this element has no value. In
1224 the case of C<select> with C<multiple> attribute, find C<option> elements with
1225 C<selected> attribute and return an array reference with all values or C<undef>
1226 if none could be found.
1229 $dom->parse('<input name="test" value="a">')->at('input')->val;
1232 $dom->parse('<textarea>b</textarea>')->at('textarea')->val;
1235 $dom->parse('<option value="c">Test</option>')->at('option')->val;
1238 $dom->parse('<select><option selected>d</option></select>')
1239 ->at('select')->val;
1242 $dom->parse('<select multiple><option selected>e</option></select>')
1243 ->at('select')->val->[0];
1247 $dom = $dom->wrap('<div></div>');
1249 Wrap HTML/XML fragment around this node, placing it as the last child of the
1250 first innermost element.
1252 # "<p>123<b>Test</b></p>"
1253 $dom->parse('<b>Test</b>')->at('b')->wrap('<p>123</p>')->root;
1255 # "<div><p><b>Test</b></p>123</div>"
1256 $dom->parse('<b>Test</b>')->at('b')->wrap('<div><p></p>123</div>')->root;
1258 # "<p><b>Test</b></p><p>123</p>"
1259 $dom->parse('<b>Test</b>')->at('b')->wrap('<p></p><p>123</p>')->root;
1261 # "<p><b>Test</b></p>"
1262 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->wrap('<b>')->root;
1266 $dom = $dom->wrap_content('<div></div>');
1268 Wrap HTML/XML fragment around this node's content, placing it as the last
1269 children of the first innermost element.
1271 # "<p><b>123Test</b></p>"
1272 $dom->parse('<p>Test<p>')->at('p')->wrap_content('<b>123</b>')->root;
1274 # "<p><b>Test</b></p><p>123</p>"
1275 $dom->parse('<b>Test</b>')->wrap_content('<p></p><p>123</p>');
1279 my $bool = $dom->xml;
1280 $dom = $dom->xml($bool);
1282 Disable HTML semantics in parser and activate case-sensitivity, defaults to
1283 auto detection based on processing instructions.
1285 =head1 COLLECTION METHODS
1287 Some L<DOM::Tiny> methods return an array-based collection object based on
1288 L<Mojo::Collection>, which can either be accessed directly as an array
1289 reference, or with the following methods.
1292 $collection->map(sub { ucfirst })->shuffle->each(sub {
1293 my ($word, $num) = @_;
1297 # Access array directly to manipulate collection
1298 $collection->[23] += 100;
1299 say for @$collection;
1303 my $new = $collection->compact;
1305 Create a new collection with all elements that are defined and not an empty
1308 # $collection contains (0, 1, undef, 2, '', 3)
1309 $collection->compact->join(', '); # "0, 1, 2, 3"
1313 my @elements = $collection->each;
1314 $collection = $collection->each(sub {...});
1316 Evaluate callback for each element in collection or return all elements as a
1317 list if none has been provided. The element will be the first argument passed
1318 to the callback and is also available as C<$_>.
1320 # Make a numbered list
1321 $collection->each(sub {
1328 my $first = $collection->first;
1329 my $first = $collection->first(qr/foo/);
1330 my $first = $collection->first(sub {...});
1331 my $first = $collection->first($method);
1332 my $first = $collection->first($method, @args);
1334 Evaluate regular expression/callback for, or call method on, each element in
1335 collection and return the first one that matched the regular expression, or for
1336 which the callback/method returned true. The element will be the first argument
1337 passed to the callback and is also available as C<$_>.
1340 my $first = $collection->first(sub { $_->$method(@args) });
1342 # Find first value that contains the word "tiny"
1343 my $interesting = $collection->first(qr/tiny/i);
1345 # Find first value that is greater than 5
1346 my $greater = $collection->first(sub { $_ > 5 });
1350 my $new = $collection->flatten;
1352 Flatten nested collections/arrays recursively and create a new collection with
1355 # $collection contains (1, [2, [3, 4], 5, [6]], 7)
1356 $collection->flatten->join(', '); # "1, 2, 3, 4, 5, 6, 7"
1360 my $new = $collection->grep(qr/foo/);
1361 my $new = $collection->grep(sub {...});
1362 my $new = $collection->grep($method);
1363 my $new = $collection->grep($method, @args);
1365 Evaluate regular expression/callback for, or call method on, each element in
1366 collection and create a new collection with all elements that matched the
1367 regular expression, or for which the callback/method returned true. The element
1368 will be the first argument passed to the callback and is also available as
1372 my $new = $collection->grep(sub { $_->$method(@args) });
1374 # Find all values that contain the word "tiny"
1375 my $interesting = $collection->grep(qr/tiny/i);
1377 # Find all values that are greater than 5
1378 my $greater = $collection->grep(sub { $_ > 5 });
1382 my $stream = $collection->join;
1383 my $stream = $collection->join("\n");
1385 Turn collection into string.
1387 # Join all values with commas
1388 $collection->join(', ');
1392 my $last = $collection->last;
1394 Return the last element in collection.
1398 my $new = $collection->map(sub {...});
1399 my $new = $collection->map($method);
1400 my $new = $collection->map($method, @args);
1402 Evaluate callback for, or call method on, each element in collection and create
1403 a new collection from the results. The element will be the first argument
1404 passed to the callback and is also available as C<$_>.
1407 my $new = $collection->map(sub { $_->$method(@args) });
1409 # Append the word "tiny" to all values
1410 my $domified = $collection->map(sub { $_ . 'tiny' });
1414 my $result = $collection->reduce(sub {...});
1415 my $result = $collection->reduce(sub {...}, $initial);
1417 Reduce elements in collection with callback, the first element will be used as
1418 initial value if none has been provided.
1420 # Calculate the sum of all values
1421 my $sum = $collection->reduce(sub { $a + $b });
1423 # Count how often each value occurs in collection
1424 my $hash = $collection->reduce(sub { $a->{$b}++; $a }, {});
1428 my $new = $collection->reverse;
1430 Create a new collection with all elements in reverse order.
1434 my $new = $collection->slice(4 .. 7);
1436 Create a new collection with all selected elements.
1438 # $collection contains ('A', 'B', 'C', 'D', 'E')
1439 $collection->slice(1, 2, 4)->join(' '); # "B C E"
1443 my $new = $collection->shuffle;
1445 Create a new collection with all elements in random order.
1449 my $size = $collection->size;
1451 Number of elements in collection.
1455 my $new = $collection->sort;
1456 my $new = $collection->sort(sub {...});
1458 Sort elements based on return value of callback and create a new collection
1461 # Sort values case-insensitive
1462 my $case_insensitive = $collection->sort(sub { uc($a) cmp uc($b) });
1466 $collection = $collection->tap(sub {...});
1468 Equivalent to L<Mojo::Base/"tap">.
1472 my $array = $collection->to_array;
1474 Turn collection into array reference.
1478 my $new = $collection->uniq;
1479 my $new = $collection->uniq(sub {...});
1480 my $new = $collection->uniq($method);
1481 my $new = $collection->uniq($method, @args);
1483 Create a new collection without duplicate elements, using the string
1484 representation of either the elements or the return value of the
1488 my $new = $collection->uniq(sub { $_->$method(@args) });
1490 # $collection contains ('foo', 'bar', 'bar', 'baz')
1491 $collection->uniq->join(' '); # "foo bar baz"
1493 # $collection contains ([1, 2], [2, 1], [3, 2])
1494 $collection->uniq(sub{ $_->[1] })->to_array; # "[[1, 2], [2, 1]]"
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<HTML::TreeBuilder>, L<XML::LibXML>, L<XML::Twig>, L<XML::Smart>
1516 =for Pod::Coverage TO_JSON