code, tests, docs
[catagits/DOM-Tiny.git] / lib / DOM / Tiny.pm
CommitLineData
a292be34 1package DOM::Tiny;
2
3use strict;
4use warnings;
5
d6512b50 6use overload
7 '@{}' => sub { shift->child_nodes },
8 '%{}' => sub { shift->attr },
9 bool => sub {1},
10 '""' => sub { shift->to_string },
11 fallback => 1;
12
13use Carp 'croak';
14use DOM::Tiny::Collection;
15use DOM::Tiny::CSS;
16use DOM::Tiny::HTML;
17use Scalar::Util qw(blessed weaken);
18
a292be34 19our $VERSION = '0.001';
20
d6512b50 21sub all_text { shift->_all_text(1, @_) }
22
23sub ancestors { _select($_[0]->_collect($_[0]->_ancestors), $_[1]) }
24
25sub append { shift->_add(1, @_) }
26sub append_content { shift->_content(1, 0, @_) }
27
28sub at {
29 my $self = shift;
30 return undef unless my $result = $self->_css->select_one(@_);
31 return $self->_build($result, $self->xml);
32}
33
34sub attr {
35 my $self = shift;
36
37 # Hash
38 my $tree = $self->tree;
39 my $attrs = $tree->[0] ne 'tag' ? {} : $tree->[2];
40 return $attrs unless @_;
41
42 # Get
43 return $attrs->{$_[0]} unless @_ > 1 || ref $_[0];
44
45 # Set
46 my $values = ref $_[0] ? $_[0] : {@_};
47 @$attrs{keys %$values} = values %$values;
48
49 return $self;
50}
51
52sub child_nodes { $_[0]->_collect(_nodes($_[0]->tree)) }
53
54sub children { _select($_[0]->_collect(_nodes($_[0]->tree, 1)), $_[1]) }
55
56sub content {
57 my $self = shift;
58
59 my $type = $self->type;
60 if ($type eq 'root' || $type eq 'tag') {
61 return $self->_content(0, 1, @_) if @_;
62 my $html = DOM::Tiny::HTML->new(xml => $self->xml);
63 return join '', map { $html->tree($_)->render } _nodes($self->tree);
64 }
65
66 return $self->tree->[1] unless @_;
67 $self->tree->[1] = shift;
68 return $self;
69}
70
71sub descendant_nodes { $_[0]->_collect(_all(_nodes($_[0]->tree))) }
72
73sub find { $_[0]->_collect(@{$_[0]->_css->select($_[1])}) }
74
75sub following { _select($_[0]->_collect(@{$_[0]->_siblings(1)->[1]}), $_[1]) }
76sub following_nodes { $_[0]->_collect(@{$_[0]->_siblings->[1]}) }
77
78sub matches { shift->_css->matches(@_) }
79
80sub namespace {
81 my $self = shift;
82
83 return undef if (my $tree = $self->tree)->[0] ne 'tag';
84
85 # Extract namespace prefix and search parents
86 my $ns = $tree->[1] =~ /^(.*?):/ ? "xmlns:$1" : undef;
87 for my $node ($tree, $self->_ancestors) {
88
89 # Namespace for prefix
90 my $attrs = $node->[2];
91 if ($ns) { $_ eq $ns and return $attrs->{$_} for keys %$attrs }
92
93 # Namespace attribute
94 elsif (defined $attrs->{xmlns}) { return $attrs->{xmlns} }
95 }
96
97 return undef;
98}
99
100sub new {
101 my $class = shift;
102 my $self = bless \DOM::Tiny::HTML->new, ref $class || $class;
103 return @_ ? $self->parse(@_) : $self;
104}
105
106sub next { $_[0]->_maybe($_[0]->_siblings(1, 0)->[1]) }
107sub next_node { $_[0]->_maybe($_[0]->_siblings(0, 0)->[1]) }
108
109sub parent {
110 my $self = shift;
111 return undef if $self->tree->[0] eq 'root';
112 return $self->_build($self->_parent, $self->xml);
113}
114
115sub parse { shift->_delegate(parse => @_) }
116
117sub preceding { _select($_[0]->_collect(@{$_[0]->_siblings(1)->[0]}), $_[1]) }
118sub preceding_nodes { $_[0]->_collect(@{$_[0]->_siblings->[0]}) }
119
120sub prepend { shift->_add(0, @_) }
121sub prepend_content { shift->_content(0, 0, @_) }
122
123sub previous { $_[0]->_maybe($_[0]->_siblings(1, -1)->[0]) }
124sub previous_node { $_[0]->_maybe($_[0]->_siblings(0, -1)->[0]) }
125
126sub remove { shift->replace('') }
127
128sub replace {
129 my ($self, $new) = @_;
130 return $self->parse($new) if (my $tree = $self->tree)->[0] eq 'root';
131 return $self->_replace($self->_parent, $tree, _nodes($self->_parse($new)));
132}
133
134sub root {
135 my $self = shift;
136 return $self unless my $tree = $self->_ancestors(1);
137 return $self->_build($tree, $self->xml);
138}
139
140sub strip {
141 my $self = shift;
142 return $self if (my $tree = $self->tree)->[0] ne 'tag';
143 return $self->_replace($tree->[3], $tree, _nodes($tree));
144}
145
146sub tag {
147 my ($self, $tag) = @_;
148 return undef if (my $tree = $self->tree)->[0] ne 'tag';
149 return $tree->[1] unless $tag;
150 $tree->[1] = $tag;
151 return $self;
152}
153
154sub tap { shift->DOM::Tiny::Collection::tap(@_) }
155
156sub text { shift->_all_text(0, @_) }
157
158sub to_string { shift->_delegate('render') }
159
160sub tree { shift->_delegate(tree => @_) }
161
162sub type { shift->tree->[0] }
163
164sub val {
165 my $self = shift;
166
167 # "option"
168 return $self->{value} // $self->text if (my $tag = $self->tag) eq 'option';
169
170 # "textarea", "input" or "button"
171 return $tag eq 'textarea' ? $self->text : $self->{value} if $tag ne 'select';
172
173 # "select"
174 my $v = $self->find('option:checked')->map('val');
175 return exists $self->{multiple} ? $v->size ? $v->to_array : undef : $v->last;
176}
177
178sub wrap { shift->_wrap(0, @_) }
179sub wrap_content { shift->_wrap(1, @_) }
180
181sub xml { shift->_delegate(xml => @_) }
182
183sub _add {
184 my ($self, $offset, $new) = @_;
185
186 return $self if (my $tree = $self->tree)->[0] eq 'root';
187
188 my $parent = $self->_parent;
189 splice @$parent, _offset($parent, $tree) + $offset, 0,
190 _link($parent, _nodes($self->_parse($new)));
191
192 return $self;
193}
194
195sub _all {
196 map { $_->[0] eq 'tag' ? ($_, _all(_nodes($_))) : ($_) } @_;
197}
198
199sub _all_text {
200 my ($self, $recurse, $trim) = @_;
201
202 # Detect "pre" tag
203 my $tree = $self->tree;
204 $trim = 1 unless defined $trim;
205 map { $_->[1] eq 'pre' and $trim = 0 } $self->_ancestors, $tree
206 if $trim && $tree->[0] ne 'root';
207
208 return _text([_nodes($tree)], $recurse, $trim);
209}
210
211sub _ancestors {
212 my ($self, $root) = @_;
213
214 return unless my $tree = $self->_parent;
215 my @ancestors;
216 do { push @ancestors, $tree }
217 while ($tree->[0] eq 'tag') && ($tree = $tree->[3]);
218 return $root ? $ancestors[-1] : @ancestors[0 .. $#ancestors - 1];
219}
220
221sub _build { shift->new->tree(shift)->xml(shift) }
222
223sub _collect {
224 my $self = shift;
225 my $xml = $self->xml;
226 return DOM::Tiny::Collection->new(map { $self->_build($_, $xml) } @_);
227}
228
229sub _content {
230 my ($self, $start, $offset, $new) = @_;
231
232 my $tree = $self->tree;
233 unless ($tree->[0] eq 'root' || $tree->[0] eq 'tag') {
234 my $old = $self->content;
235 return $self->content($start ? "$old$new" : "$new$old");
236 }
237
238 $start = $start ? ($#$tree + 1) : _start($tree);
239 $offset = $offset ? $#$tree : 0;
240 splice @$tree, $start, $offset, _link($tree, _nodes($self->_parse($new)));
241
242 return $self;
243}
244
245sub _css { DOM::Tiny::CSS->new(tree => shift->tree) }
246
247sub _delegate {
248 my ($self, $method) = (shift, shift);
249 return $$self->$method unless @_;
250 $$self->$method(@_);
251 return $self;
252}
253
254sub _link {
255 my ($parent, @children) = @_;
256
257 # Link parent to children
258 for my $node (@children) {
259 my $offset = $node->[0] eq 'tag' ? 3 : 2;
260 $node->[$offset] = $parent;
261 weaken $node->[$offset];
262 }
263
264 return @children;
265}
266
267sub _maybe { $_[1] ? $_[0]->_build($_[1], $_[0]->xml) : undef }
268
269sub _nodes {
270 return unless my $tree = shift;
271 my @nodes = @$tree[_start($tree) .. $#$tree];
272 return shift() ? grep { $_->[0] eq 'tag' } @nodes : @nodes;
273}
274
275sub _offset {
276 my ($parent, $child) = @_;
277 my $i = _start($parent);
278 $_ eq $child ? last : $i++ for @$parent[$i .. $#$parent];
279 return $i;
280}
281
282sub _parent { $_[0]->tree->[$_[0]->type eq 'tag' ? 3 : 2] }
283
284sub _parse { DOM::Tiny::HTML->new(xml => shift->xml)->parse(shift)->tree }
285
286sub _replace {
287 my ($self, $parent, $tree, @nodes) = @_;
288 splice @$parent, _offset($parent, $tree), 1, _link($parent, @nodes);
289 return $self->parent;
290}
291
292sub _select {
293 my ($collection, $selector) = @_;
294 return $collection unless $selector;
295 return $collection->new(grep { $_->matches($selector) } @$collection);
296}
297
298sub _siblings {
299 my ($self, $tags, $i) = @_;
300
301 return [] unless my $parent = $self->parent;
302
303 my $tree = $self->tree;
304 my (@before, @after, $match);
305 for my $node (_nodes($parent->tree)) {
306 ++$match and next if !$match && $node eq $tree;
307 next if $tags && $node->[0] ne 'tag';
308 $match ? push @after, $node : push @before, $node;
309 }
310
311 return defined $i ? [$before[$i], $after[$i]] : [\@before, \@after];
312}
313
314sub _squish {
315 my $str = shift;
316 $str =~ s/^\s+//;
317 $str =~ s/\s+$//;
318 $str =~ s/\s+/ /g;
319 return $str;
320}
321
322sub _start { $_[0][0] eq 'root' ? 1 : 4 }
323
324sub _text {
325 my ($nodes, $recurse, $trim) = @_;
326
327 # Merge successive text nodes
328 my $i = 0;
329 while (my $next = $nodes->[$i + 1]) {
330 ++$i and next unless $nodes->[$i][0] eq 'text' && $next->[0] eq 'text';
331 splice @$nodes, $i, 2, ['text', $nodes->[$i][1] . $next->[1]];
332 }
333
334 my $text = '';
335 for my $node (@$nodes) {
336 my $type = $node->[0];
337
338 # Text
339 my $chunk = '';
340 if ($type eq 'text') { $chunk = $trim ? _squish $node->[1] : $node->[1] }
341
342 # CDATA or raw text
343 elsif ($type eq 'cdata' || $type eq 'raw') { $chunk = $node->[1] }
344
345 # Nested tag
346 elsif ($type eq 'tag' && $recurse) {
347 no warnings 'recursion';
348 $chunk = _text([_nodes($node)], 1, $node->[1] eq 'pre' ? 0 : $trim);
349 }
350
351 # Add leading whitespace if punctuation allows it
352 $chunk = " $chunk" if $text =~ /\S\z/ && $chunk =~ /^[^.!?,;:\s]+/;
353
354 # Trim whitespace blocks
355 $text .= $chunk if $chunk =~ /\S+/ || !$trim;
356 }
357
358 return $text;
359}
360
361sub _wrap {
362 my ($self, $content, $new) = @_;
363
364 $content = 1 if (my $tree = $self->tree)->[0] eq 'root';
365 $content = 0 if $tree->[0] ne 'root' && $tree->[0] ne 'tag';
366
367 # Find innermost tag
368 my $current;
369 my $first = $new = $self->_parse($new);
370 $current = $first while $first = (_nodes($first, 1))[0];
371 return $self unless $current;
372
373 # Wrap content
374 if ($content) {
375 push @$current, _link($current, _nodes($tree));
376 splice @$tree, _start($tree), $#$tree, _link($tree, _nodes($new));
377 return $self;
378 }
379
380 # Wrap element
381 $self->_replace($self->_parent, $tree, _nodes($new));
382 push @$current, _link($current, $tree);
383 return $self;
384}
385
a292be34 3861;
387
d6512b50 388=encoding utf8
389
a292be34 390=head1 NAME
391
d6512b50 392DOM::Tiny - Minimalistic HTML/XML DOM parser with CSS selectors
a292be34 393
394=head1 SYNOPSIS
395
d6512b50 396 use DOM::Tiny;
397
398 # Parse
399 my $dom = DOM::Tiny->new('<div><p id="a">Test</p><p id="b">123</p></div>');
400
401 # Find
402 say $dom->at('#b')->text;
403 say $dom->find('p')->map('text')->join("\n");
404 say $dom->find('[id]')->map(attr => 'id')->join("\n");
405
406 # Iterate
407 $dom->find('p[id]')->reverse->each(sub { say $_->{id} });
408
409 # Loop
410 for my $e ($dom->find('p[id]')->each) {
411 say $e->{id}, ':', $e->text;
412 }
413
414 # Modify
415 $dom->find('div p')->last->append('<p id="c">456</p>');
416 $dom->find(':not(p)')->map('strip');
417
418 # Render
419 say "$dom";
420
a292be34 421=head1 DESCRIPTION
422
d6512b50 423L<DOM::Tiny> is a minimalistic and relaxed HTML/XML DOM parser with CSS
424selector support based on L<Mojo::DOM>. It will even try to interpret broken
425HTML and XML, so you should not use it for validation.
426
427=head1 NODES AND ELEMENTS
428
429When we parse an HTML/XML fragment, it gets turned into a tree of nodes.
430
431 <!DOCTYPE html>
432 <html>
433 <head><title>Hello</title></head>
434 <body>World!</body>
435 </html>
436
437There are currently eight different kinds of nodes, C<cdata>, C<comment>,
438C<doctype>, C<pi>, C<raw>, C<root>, C<tag> and C<text>. Elements are nodes of
439the type C<tag>.
440
441 root
442 |- doctype (html)
443 +- tag (html)
444 |- tag (head)
445 | +- tag (title)
446 | +- raw (Hello)
447 +- tag (body)
448 +- text (World!)
449
450While all node types are represented as L<DOM::Tiny> objects, some methods like
451L</"attr"> and L</"namespace"> only apply to elements.
452
453=head1 CASE-SENSITIVITY
454
455L<DOM::Tiny> defaults to HTML semantics, that means all tags and attribute
456names are lowercased and selectors need to be lowercase as well.
457
458 # HTML semantics
459 my $dom = DOM::Tiny->new('<P ID="greeting">Hi!</P>');
460 say $dom->at('p[id]')->text;
461
462If XML processing instructions are found, the parser will automatically switch
463into XML mode and everything becomes case-sensitive.
464
465 # XML semantics
466 my $dom = DOM::Tiny->new('<?xml version="1.0"?><P ID="greeting">Hi!</P>');
467 say $dom->at('P[ID]')->text;
468
469XML detection can also be disabled with the L</"xml"> method.
470
471 # Force XML semantics
472 my $dom = DOM::Tiny->new->xml(1)->parse('<P ID="greeting">Hi!</P>');
473 say $dom->at('P[ID]')->text;
474
475 # Force HTML semantics
476 my $dom = DOM::Tiny->new->xml(0)->parse('<P ID="greeting">Hi!</P>');
477 say $dom->at('p[id]')->text;
478
479=head1 METHODS
480
481L<DOM::Tiny> implements the following methods.
482
483=head2 all_text
484
485 my $trimmed = $dom->all_text;
486 my $untrimmed = $dom->all_text(0);
487
488Extract text content from all descendant nodes of this element, smart
489whitespace trimming is enabled by default.
490
491 # "foo bar baz"
492 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text;
493
494 # "foo\nbarbaz\n"
495 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text(0);
496
497=head2 ancestors
498
499 my $collection = $dom->ancestors;
500 my $collection = $dom->ancestors('div ~ p');
501
502Find all ancestor elements of this node matching the CSS selector and return a
503L<DOM::Tiny::Collection> object containing these elements as L<DOM::Tiny>
504objects. All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are supported.
505
506 # List tag names of ancestor elements
507 say $dom->ancestors->map('tag')->join("\n");
508
509=head2 append
510
511 $dom = $dom->append('<p>I ♥ DOM::Tiny!</p>');
512
513Append HTML/XML fragment to this node.
514
515 # "<div><h1>Test</h1><h2>123</h2></div>"
516 $dom->parse('<div><h1>Test</h1></div>')
517 ->at('h1')->append('<h2>123</h2>')->root;
518
519 # "<p>Test 123</p>"
520 $dom->parse('<p>Test</p>')->at('p')
521 ->child_nodes->first->append(' 123')->root;
522
523=head2 append_content
524
525 $dom = $dom->append_content('<p>I ♥ DOM::Tiny!</p>');
526
527Append HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
528node's content.
529
530 # "<div><h1>Test123</h1></div>"
531 $dom->parse('<div><h1>Test</h1></div>')
532 ->at('h1')->append_content('123')->root;
533
534 # "<!-- Test 123 --><br>"
535 $dom->parse('<!-- Test --><br>')
536 ->child_nodes->first->append_content('123 ')->root;
537
538 # "<p>Test<i>123</i></p>"
539 $dom->parse('<p>Test</p>')->at('p')->append_content('<i>123</i>')->root;
540
541=head2 at
542
543 my $result = $dom->at('div ~ p');
544
545Find first descendant element of this element matching the CSS selector and
546return it as a L<DOM::Tiny> object or return C<undef> if none could be found.
547All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are supported.
548
549 # Find first element with "svg" namespace definition
550 my $namespace = $dom->at('[xmlns\:svg]')->{'xmlns:svg'};
551
552=head2 attr
553
554 my $hash = $dom->attr;
555 my $foo = $dom->attr('foo');
556 $dom = $dom->attr({foo => 'bar'});
557 $dom = $dom->attr(foo => 'bar');
558
559This element's attributes.
560
561 # Remove an attribute
562 delete $dom->attr->{id};
563
564 # Attribute without value
565 $dom->attr(selected => undef);
566
567 # List id attributes
568 say $dom->find('*')->map(attr => 'id')->compact->join("\n");
569
570=head2 child_nodes
571
572 my $collection = $dom->child_nodes;
573
574Return a L<DOM::Tiny::Collection> object containing all child nodes of this
575element as L<DOM::Tiny> objects.
576
577 # "<p><b>123</b></p>"
578 $dom->parse('<p>Test<b>123</b></p>')->at('p')->child_nodes->first->remove;
579
580 # "<!DOCTYPE html>"
581 $dom->parse('<!DOCTYPE html><b>123</b>')->child_nodes->first;
582
583 # " Test "
584 $dom->parse('<b>123</b><!-- Test -->')->child_nodes->last->content;
585
586=head2 children
587
588 my $collection = $dom->children;
589 my $collection = $dom->children('div ~ p');
590
591Find all child elements of this element matching the CSS selector and return a
592L<DOM::Tiny::Collection> object containing these elements as L<DOM::Tiny>
593objects. All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are supported.
594
595 # Show tag name of random child element
596 say $dom->children->shuffle->first->tag;
597
598=head2 content
599
600 my $str = $dom->content;
601 $dom = $dom->content('<p>I ♥ DOM::Tiny!</p>');
602
603Return this node's content or replace it with HTML/XML fragment (for C<root>
604and C<tag> nodes) or raw content.
605
606 # "<b>Test</b>"
607 $dom->parse('<div><b>Test</b></div>')->at('div')->content;
608
609 # "<div><h1>123</h1></div>"
610 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('123')->root;
611
612 # "<p><i>123</i></p>"
613 $dom->parse('<p>Test</p>')->at('p')->content('<i>123</i>')->root;
614
615 # "<div><h1></h1></div>"
616 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('')->root;
617
618 # " Test "
619 $dom->parse('<!-- Test --><br>')->child_nodes->first->content;
620
621 # "<div><!-- 123 -->456</div>"
622 $dom->parse('<div><!-- Test -->456</div>')
623 ->at('div')->child_nodes->first->content(' 123 ')->root;
624
625=head2 descendant_nodes
626
627 my $collection = $dom->descendant_nodes;
628
629Return a L<DOM::Tiny::Collection> object containing all descendant nodes of
630this element as L<DOM::Tiny> objects.
631
632 # "<p><b>123</b></p>"
633 $dom->parse('<p><!-- Test --><b>123<!-- 456 --></b></p>')
634 ->descendant_nodes->grep(sub { $_->type eq 'comment' })
635 ->map('remove')->first;
636
637 # "<p><b>test</b>test</p>"
638 $dom->parse('<p><b>123</b>456</p>')
639 ->at('p')->descendant_nodes->grep(sub { $_->type eq 'text' })
640 ->map(content => 'test')->first->root;
641
642=head2 find
643
644 my $collection = $dom->find('div ~ p');
645
646Find all descendant elements of this element matching the CSS selector and
647return a L<DOM::Tiny::Collection> object containing these elements as
648L<DOM::Tiny> objects. All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are
649supported.
650
651 # Find a specific element and extract information
652 my $id = $dom->find('div')->[23]{id};
653
654 # Extract information from multiple elements
655 my @headers = $dom->find('h1, h2, h3')->map('text')->each;
656
657 # Count all the different tags
658 my $hash = $dom->find('*')->reduce(sub { $a->{$b->tag}++; $a }, {});
659
660 # Find elements with a class that contains dots
661 my @divs = $dom->find('div.foo\.bar')->each;
662
663=head2 following
664
665 my $collection = $dom->following;
666 my $collection = $dom->following('div ~ p');
667
668Find all sibling elements after this node matching the CSS selector and return
669a L<DOM::Tiny::Collection> object containing these elements as L<DOM::Tiny>
670objects. All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are supported.
671
672 # List tags of sibling elements after this node
673 say $dom->following->map('tag')->join("\n");
674
675=head2 following_nodes
676
677 my $collection = $dom->following_nodes;
678
679Return a L<DOM::Tiny::Collection> object containing all sibling nodes after
680this node as L<DOM::Tiny> objects.
681
682 # "C"
683 $dom->parse('<p>A</p><!-- B -->C')->at('p')->following_nodes->last->content;
684
685=head2 matches
686
687 my $bool = $dom->matches('div ~ p');
688
689Check if this element matches the CSS selector. All selectors from
690L<DOM::Tiny::CSS/"SELECTORS"> are supported.
691
692 # True
693 $dom->parse('<p class="a">A</p>')->at('p')->matches('.a');
694 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[class]');
695
696 # False
697 $dom->parse('<p class="a">A</p>')->at('p')->matches('.b');
698 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[id]');
699
700=head2 namespace
701
702 my $namespace = $dom->namespace;
703
704Find this element's namespace or return C<undef> if none could be found.
705
706 # Find namespace for an element with namespace prefix
707 my $namespace = $dom->at('svg > svg\:circle')->namespace;
708
709 # Find namespace for an element that may or may not have a namespace prefix
710 my $namespace = $dom->at('svg > circle')->namespace;
711
712=head2 new
713
714 my $dom = DOM::Tiny->new;
715 my $dom = DOM::Tiny->new('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
716
717Construct a new scalar-based L<DOM::Tiny> object and L</"parse"> HTML/XML
718fragment if necessary.
719
720=head2 next
721
722 my $sibling = $dom->next;
723
724Return L<DOM::Tiny> object for next sibling element or C<undef> if there are no
725more siblings.
726
727 # "<h2>123</h2>"
728 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h1')->next;
729
730=head2 next_node
731
732 my $sibling = $dom->next_node;
733
734Return L<DOM::Tiny> object for next sibling node or C<undef> if there are no
735more siblings.
736
737 # "456"
738 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
739 ->at('b')->next_node->next_node;
740
741 # " Test "
742 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
743 ->at('b')->next_node->content;
744
745=head2 parent
746
747 my $parent = $dom->parent;
748
749Return L<DOM::Tiny> object for parent of this node or C<undef> if this node has
750no parent.
751
752=head2 parse
753
754 $dom = $dom->parse('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
755
756Parse HTML/XML fragment with L<DOM::Tiny::HTML>.
757
758 # Parse XML
759 my $dom = DOM::Tiny->new->xml(1)->parse($xml);
760
761=head2 preceding
762
763 my $collection = $dom->preceding;
764 my $collection = $dom->preceding('div ~ p');
765
766Find all sibling elements before this node matching the CSS selector and return
767a L<DOM::Tiny::Collection> object containing these elements as L<DOM::Tiny>
768objects. All selectors from L<DOM::Tiny::CSS/"SELECTORS"> are supported.
769
770 # List tags of sibling elements before this node
771 say $dom->preceding->map('tag')->join("\n");
772
773=head2 preceding_nodes
774
775 my $collection = $dom->preceding_nodes;
776
777Return a L<DOM::Tiny::Collection> object containing all sibling nodes before
778this node as L<DOM::Tiny> objects.
779
780 # "A"
781 $dom->parse('A<!-- B --><p>C</p>')->at('p')->preceding_nodes->first->content;
782
783=head2 prepend
784
785 $dom = $dom->prepend('<p>I ♥ DOM::Tiny!</p>');
786
787Prepend HTML/XML fragment to this node.
788
789 # "<div><h1>Test</h1><h2>123</h2></div>"
790 $dom->parse('<div><h2>123</h2></div>')
791 ->at('h2')->prepend('<h1>Test</h1>')->root;
792
793 # "<p>Test 123</p>"
794 $dom->parse('<p>123</p>')
795 ->at('p')->child_nodes->first->prepend('Test ')->root;
796
797=head2 prepend_content
798
799 $dom = $dom->prepend_content('<p>I ♥ DOM::Tiny!</p>');
800
801Prepend HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
802node's content.
803
804 # "<div><h2>Test123</h2></div>"
805 $dom->parse('<div><h2>123</h2></div>')
806 ->at('h2')->prepend_content('Test')->root;
807
808 # "<!-- Test 123 --><br>"
809 $dom->parse('<!-- 123 --><br>')
810 ->child_nodes->first->prepend_content(' Test')->root;
811
812 # "<p><i>123</i>Test</p>"
813 $dom->parse('<p>Test</p>')->at('p')->prepend_content('<i>123</i>')->root;
814
815=head2 previous
816
817 my $sibling = $dom->previous;
818
819Return L<DOM::Tiny> object for previous sibling element or C<undef> if there
820are no more siblings.
821
822 # "<h1>Test</h1>"
823 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h2')->previous;
824
825=head2 previous_node
826
827 my $sibling = $dom->previous_node;
828
829Return L<DOM::Tiny> object for previous sibling node or C<undef> if there are
830no more siblings.
831
832 # "123"
833 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
834 ->at('b')->previous_node->previous_node;
835
836 # " Test "
837 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
838 ->at('b')->previous_node->content;
839
840=head2 remove
841
842 my $parent = $dom->remove;
843
844Remove this node and return L</"root"> (for C<root> nodes) or L</"parent">.
845
846 # "<div></div>"
847 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->remove;
848
849 # "<p><b>456</b></p>"
850 $dom->parse('<p>123<b>456</b></p>')
851 ->at('p')->child_nodes->first->remove->root;
852
853=head2 replace
854
855 my $parent = $dom->replace('<div>I ♥ DOM::Tiny!</div>');
856
857Replace this node with HTML/XML fragment and return L</"root"> (for C<root>
858nodes) or L</"parent">.
859
860 # "<div><h2>123</h2></div>"
861 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->replace('<h2>123</h2>');
862
863 # "<p><b>123</b></p>"
864 $dom->parse('<p>Test</p>')
865 ->at('p')->child_nodes->[0]->replace('<b>123</b>')->root;
866
867=head2 root
868
869 my $root = $dom->root;
870
871Return L<DOM::Tiny> object for C<root> node.
872
873=head2 strip
874
875 my $parent = $dom->strip;
876
877Remove this element while preserving its content and return L</"parent">.
878
879 # "<div>Test</div>"
880 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->strip;
881
882=head2 tag
883
884 my $tag = $dom->tag;
885 $dom = $dom->tag('div');
886
887This element's tag name.
888
889 # List tag names of child elements
890 say $dom->children->map('tag')->join("\n");
891
892=head2 tap
893
894 $dom = $dom->tap(sub {...});
895
896Alias for L<Mojo::Base/"tap">.
897
898=head2 text
899
900 my $trimmed = $dom->text;
901 my $untrimmed = $dom->text(0);
902
903Extract text content from this element only (not including child elements),
904smart whitespace trimming is enabled by default.
905
906 # "foo baz"
907 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text;
908
909 # "foo\nbaz\n"
910 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text(0);
911
912=head2 to_string
913
914 my $str = $dom->to_string;
915
916Render this node and its content to HTML/XML.
917
918 # "<b>Test</b>"
919 $dom->parse('<div><b>Test</b></div>')->at('div b')->to_string;
920
921=head2 tree
922
923 my $tree = $dom->tree;
924 $dom = $dom->tree(['root']);
925
926Document Object Model. Note that this structure should only be used very
927carefully since it is very dynamic.
928
929=head2 type
930
931 my $type = $dom->type;
932
933This node's type, usually C<cdata>, C<comment>, C<doctype>, C<pi>, C<raw>,
934C<root>, C<tag> or C<text>.
935
936 # "cdata"
937 $dom->parse('<![CDATA[Test]]>')->child_nodes->first->type;
938
939 # "comment"
940 $dom->parse('<!-- Test -->')->child_nodes->first->type;
941
942 # "doctype"
943 $dom->parse('<!DOCTYPE html>')->child_nodes->first->type;
944
945 # "pi"
946 $dom->parse('<?xml version="1.0"?>')->child_nodes->first->type;
947
948 # "raw"
949 $dom->parse('<title>Test</title>')->at('title')->child_nodes->first->type;
950
951 # "root"
952 $dom->parse('<p>Test</p>')->type;
953
954 # "tag"
955 $dom->parse('<p>Test</p>')->at('p')->type;
956
957 # "text"
958 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->type;
959
960=head2 val
961
962 my $value = $dom->val;
963
964Extract value from form element (such as C<button>, C<input>, C<option>,
965C<select> and C<textarea>) or return C<undef> if this element has no value. In
966the case of C<select> with C<multiple> attribute, find C<option> elements with
967C<selected> attribute and return an array reference with all values or C<undef>
968if none could be found.
969
970 # "a"
971 $dom->parse('<input name="test" value="a">')->at('input')->val;
972
973 # "b"
974 $dom->parse('<textarea>b</textarea>')->at('textarea')->val;
975
976 # "c"
977 $dom->parse('<option value="c">Test</option>')->at('option')->val;
978
979 # "d"
980 $dom->parse('<select><option selected>d</option></select>')
981 ->at('select')->val;
982
983 # "e"
984 $dom->parse('<select multiple><option selected>e</option></select>')
985 ->at('select')->val->[0];
986
987=head2 wrap
988
989 $dom = $dom->wrap('<div></div>');
990
991Wrap HTML/XML fragment around this node, placing it as the last child of the
992first innermost element.
993
994 # "<p>123<b>Test</b></p>"
995 $dom->parse('<b>Test</b>')->at('b')->wrap('<p>123</p>')->root;
996
997 # "<div><p><b>Test</b></p>123</div>"
998 $dom->parse('<b>Test</b>')->at('b')->wrap('<div><p></p>123</div>')->root;
999
1000 # "<p><b>Test</b></p><p>123</p>"
1001 $dom->parse('<b>Test</b>')->at('b')->wrap('<p></p><p>123</p>')->root;
1002
1003 # "<p><b>Test</b></p>"
1004 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->wrap('<b>')->root;
1005
1006=head2 wrap_content
1007
1008 $dom = $dom->wrap_content('<div></div>');
1009
1010Wrap HTML/XML fragment around this node's content, placing it as the last
1011children of the first innermost element.
1012
1013 # "<p><b>123Test</b></p>"
1014 $dom->parse('<p>Test<p>')->at('p')->wrap_content('<b>123</b>')->root;
1015
1016 # "<p><b>Test</b></p><p>123</p>"
1017 $dom->parse('<b>Test</b>')->wrap_content('<p></p><p>123</p>');
1018
1019=head2 xml
1020
1021 my $bool = $dom->xml;
1022 $dom = $dom->xml($bool);
1023
1024Disable HTML semantics in parser and activate case-sensitivity, defaults to
1025auto detection based on processing instructions.
1026
1027=head1 OPERATORS
1028
1029L<DOM::Tiny> overloads the following operators.
1030
1031=head2 array
1032
1033 my @nodes = @$dom;
1034
1035Alias for L</"child_nodes">.
1036
1037 # "<!-- Test -->"
1038 $dom->parse('<!-- Test --><b>123</b>')->[0];
1039
1040=head2 bool
1041
1042 my $bool = !!$dom;
1043
1044Always true.
1045
1046=head2 hash
1047
1048 my %attrs = %$dom;
1049
1050Alias for L</"attr">.
1051
1052 # "test"
1053 $dom->parse('<div id="test">Test</div>')->at('div')->{id};
1054
1055=head2 stringify
1056
1057 my $str = "$dom";
1058
1059Alias for L</"to_string">.
1060
a292be34 1061=head1 BUGS
1062
1063Report any issues on the public bugtracker.
1064
1065=head1 AUTHOR
1066
1067Dan Book <dbook@cpan.org>
1068
1069=head1 COPYRIGHT AND LICENSE
1070
1071This software is Copyright (c) 2015 by Dan Book.
1072
1073This is free software, licensed under:
1074
1075 The Artistic License 2.0 (GPL Compatible)
1076
1077=head1 SEE ALSO
1078
d6512b50 1079L<Mojo::DOM>, L<XML::LibXML>, L<XML::Twig>, L<HTML::TreeBuilder>, L<XML::Smart>