Note that there are some explanatory texts on larger screens.

plurals
  1. POWrapping a series of elements between two h2 tags with jquery
    text
    copied!<p>I currently have a page being dynamically created like below:</p> <pre><code>&lt;h2&gt;a Heading&lt;/h2&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; </code></pre> <pre><code>&lt;h2&gt;a Heading&lt;/h2&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; </code></pre> <p>What I'm looking to do is to use jQuery to wrap the <code>h2</code> and <code>p</code> tags till the next <code>h2</code> tag: e.g.:</p> <pre><code>&lt;div class="headingName"&gt; &lt;h2&gt;a Heading&lt;/h2&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;/div&gt; </code></pre> <pre><code>&lt;div class="headingName"&gt; &lt;h2&gt;a Heading&lt;/h2&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;p&gt;a paragraph&lt;/p&gt; &lt;/div&gt; </code></pre> <p>So far I unsuccessfully managed this, but have gotten close using code from a user here (can't find the link to the original article):</p> <pre><code>$('.report-content h2').each(function(){ var $set = $(); var nxt = this.nextSibling; while(nxt) { if(!$(nxt).is('.report-content h2')) { $set.push(nxt); nxt = nxt.nextSibling; } else break; } $set.wrapAll('&lt;div class="content" /&gt;'); }); </code></pre> <p>What I get is the <code>div</code> being wrapped around only the <code>p</code> tags but need to include the associated <code>h2</code> tag, usually the one above the <code>p</code> tags.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload