JQuery: replace and close open tags
<p>I want to divide the content of an element in divs. The delimiter is <code>&lt;hr/&gt;</code> and all open tags should be closed before the closing-div and (if needed) reopened after the reopened div tag. My naive idea was to traverse with jQuery through an elements children, replace all occurrences of <code>&lt;hr/&gt;</code> with <code>&lt;/div&gt;&lt;div&gt;</code> and close all open tags (up to a certain level) before that. I don't know how to reopen them though.</p>

<p>Example:</p>

<pre><code>&lt;div id="content"&gt;
    &lt;p&gt;Bla some text
    &lt;hr/&gt;
    Some more text
    &lt;/p&gt;
&lt;/div&gt;
</code></pre>

<p>will become:</p>

<pre><code>&lt;div id="content"&gt;
    &lt;div&gt;
        &lt;p&gt;Bla some text
        &lt;/p&gt;
    &lt;/div&gt;&lt;div&gt;
        &lt;p&gt;Some more text
        &lt;/p&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>What I had in mind was to simply visit each tag in their order of appearance, add them to a stack when they open, remove them when they're closed again, if I find a delimiter, close all tags in the stack (but don't remove them), insert the <code>&lt;div/&gt;</code> tag, reopen all tags on the stack in reverse order. continue until end and close all still open tags.</p>

<p>The purpose of this is to chunk a text into predefined parts. It is for a text pagination and the divs are the pages. I want the user to be able to manually specify the break, even inside of ul's, p's and so on.</p>

<p>Any help is appreciated.</p>
