Reputation: 226
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:
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:
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!
Upvotes: 4
Views: 655
Reputation: 4808
I think I got the answer you were looking for, just tweaked the last selector to be:
jQuery('h3:eq(2)').nextUntil('p:last').andSelf().wrapAll('<div class="col3" />');
see http://codepen.io/ian-pvd/pen/GKryq
Upvotes: 2
Reputation: 92963
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:
jQuery('#content>h3:nth-of-type(3)').nextUntil('div').andSelf().wrapAll('<div class="col3" />');
jQuery('#content>h3:nth-of-type(1)').nextUntil('div').andSelf().wrapAll('<div class="col2" />');
jQuery('#content>h2').nextUntil('div').andSelf().wrapAll('<div class="col1" />');
Upvotes: 2