Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
added wrap method to Mojo::DOM
  • Loading branch information
kraih committed Feb 4, 2014
1 parent 8b59fd9 commit 57f1d72
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

4.76 2014-02-04
- Added wrap method to Mojo::DOM.
- Updated IO::Socket::IP requirement to 0.20 for certain bug fixes.
- Improved Mojo::DOM::HTML to generate better HTML.

Expand Down
29 changes: 29 additions & 0 deletions lib/Mojo/DOM.pm
Expand Up @@ -9,6 +9,7 @@ use overload
# "Fry: This snow is beautiful. I'm glad global warming never happened.
# Leela: Actually, it did. But thank God nuclear winter canceled it out."
use Carp 'croak';
use List::Util 'first';
use Mojo::Collection;
use Mojo::DOM::CSS;
use Mojo::DOM::HTML;
Expand Down Expand Up @@ -200,6 +201,25 @@ sub type {
return $self;
}

sub wrap {
my ($self, $new) = @_;

my $tree = $self->tree;
return $self if $tree->[0] eq 'root';

# Find innermost tag
my $current;
my $first = $new = $self->_parse("$new");
$current = $first while $first = first { $_->[0] eq 'tag' } _nodes($first);
return $self unless $current;

# Wrap element
$self->_replace($tree, $new);
splice @$current, _start($current), 0, _link(['root', $tree], $current);

return $self;
}

sub xml { shift->_delegate(xml => @_) }

sub _add {
Expand Down Expand Up @@ -793,6 +813,15 @@ This element's type.
# List types of child elements
say $dom->children->type;
=head2 wrap
$dom = $dom->wrap('<div></div>');
Wrap HTML/XML fragment around this element.
# "<div><h1>A</h1>B</div>"
$dom->parse('<h1>A</h1>')->at('h1')->wrap('<div>B</div>')->root;
=head2 xml
my $bool = $dom->xml;
Expand Down
11 changes: 11 additions & 0 deletions t/mojo/dom.t
Expand Up @@ -2010,6 +2010,17 @@ $dom->at('b')->prepend_content('<e>Mojo</e>');
is $dom->at('e')->parent->type, 'b', 'right element';
is $dom->all_text, 'Mojo Test', 'right text';

# Wrap elements
$dom = Mojo::DOM->new('<a>Test</a>');
is $dom->wrap('<no></no>')->root->to_xml, '<a>Test</a>', 'right result';
is $dom->at('a')->wrap('A')->type, 'a', 'right element';
is "$dom", '<a>Test</a>', 'right result';
is $dom->at('a')->wrap('<b></b>')->type, 'a', 'right element';
is "$dom", '<b><a>Test</a></b>', 'right result';
is $dom->at('a')->wrap('C<c><d>D</d><e>E</e></c>F')->parent->type, 'd',
'right element';
is "$dom", '<b>C<c><d><a>Test</a>D</d><e>E</e></c>F</b>', 'right result';

# Broken "div" in "td"
$dom = Mojo::DOM->new(<<EOF);
<table>
Expand Down

0 comments on commit 57f1d72

Please sign in to comment.