Looking to use jQuery to wrap an arbitrary amount of user supplied content into effectively three columns. The initial HTML would looks like this:
<div#content>
<h2>Page Title</h2>
<p>Some arbitrary number of paragraphs followed by some arbitrary number of biographies, with an arbitrary number of paragraphs.</p>
<p>Paragraph.</p>
<h3>First Person</h3>
<p>Paragraph.</p>
<p>Paragraph.</p>
<h3>Second Person</h3>
<p>Paragraph.</p>
<h3>Person Three</h3>
<p>Paragraph.</p>
<h3>Person Four</h3>
<p>Paragraph.</p>
<h3>Person Five</h3>
<p>Paragraph.</p>
</div>
The goal is to wrap the content into three columns:
- The first H2 and subsequent paragraphs would be in column one.
- The next two H3s and subsequent paragraphs would be in column two.
- The remaining H3s (in this case three, it could be more) would be in column three.
So…
<div#content>
<div.col1>
<h2>Page Title</h2>
<p>Paragraph.</p>
<p>Paragraph.</p>
</div>
<div.col2>
<h3>First Person</h3>
<p>Paragraph.</p>
<p>Paragraph.</p>
<h3>Second Person</h3>
<p>Paragraph.</p>
</div>
<div.col3>
<h3>Person Three</h3>
<p>Paragraph.</p>
<h3>Person Four</h3>
<p>Paragraph.</p>
<h3>Person Five</h3>
<p>Paragraph.</p>
<!-- etc. -->
</div>
</div>
I have a CodePen set up here: http://codepen.io/ian-pvd/pen/GKryq
It is using the following method:
jQuery('h2').nextUntil('h3').andSelf().wrapAll('<div class="col1" />');
jQuery('h3:nth-of-type(1)').nextUntil('h3:nth-of-type(3)').andSelf().wrapAll('<div class="col2" />');
jQuery('h3:nth-of-type(3)').nextUntil('p:last-of-type').wrapAll('<div class="col3" />');
This works right up until the third column, where I’m having trouble wrapping whatever content remains in the third column.
I’ve checked these other questions, which offered some help:
- Wrap Multiple <p> elements into <div> between <h3>
- need to wrap h3 and div in wrapper div with jquery
- jQuery Wrap a div from H2 until last paragraph
But the solutions are a more specific to wrapping from H2 to H2, and not switching between H2 and H3 tags, or including two H3 tags in one set.
Trying to convince the user to enter content differently / separately has already been ruled out for me.
Is there a simple way to do this?
Thanks for your help!
The last selector,
h3:nth-of-type(3), isn’t matching as expected because you’ve wrapped up the first and second h3 already; the h3 that used to be third is now first-of-type.Try wrapping the columns in reverse order instead: