Could you provide some input HTML that's valid, and explain by what rules the <h3> got wrapped up in a <div> along with the two <p>'s, instead of the <p> preceding the <h3> being wrapped along with the preceding <h2>?

Anyway, I agree that Mojo::DOM is nice. Maybe this is something to get started with:

use warnings; use strict; use Mojo::DOM; my $html = "<h1>a</h1>\n<p>b</p>\n<h2>c</h2>\n<p>d</p>\n" ."<h3>e</h3>\n<p>f</p>\n<h2>g</h2>\n<p>h</p>\n<h2>i</h2>\n" ."<h1>j</h1>\n<h2>k</h2>\n"; my $dom = Mojo::DOM->new($html); $dom->find('h2')->each(sub { my $next = $_->next; my $new = $_->wrap('<div></div>'); if ( $next && !$next->matches('h1') ) { $new->append($next); $next->remove; } }); print "$dom";

In reply to Re: Wrapping HTML "sections" with a div by haukex
in thread Wrapping HTML "sections" with a div by nysus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.