1

I have a snippet of consistent mark-up that I would like to .wrapAll with a class. I am trying to identify the <h2> and the next two elements.

The elements that come before this snippet and after isn't consistent so I can't use .next to the next <h2> etc., but the .UniqueClass on the <h2> is something I think I can key on?

I've tried the following but it is not working.
How would I wrap the <h2>, <p>, and div.accordion in one class?

var $set = $('h2.uniqueClass').children();
for (var i = 0, len = $set.length; i < len; i += 2) {
  $set.slice(i, i + 2).wrapAll('<div class="test"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2 class "uniqueClass">Headline</h2>
<p>A p tag always follows.</p>
<div class="accordion">An accordion always comes after the p tag.</div>
showdev
  • 28,454
  • 37
  • 55
  • 73
ndek
  • 13
  • 2

2 Answers2

2

You is a missing = on the first element 'class='

There are a couple of answers on this topic here and here $(".uniqueClass").next().andSelf().next().andSelf().wrapAll('<div class="test"/>');

or

var $set = $('.content').children();    
for(var i=0, len = $set.length; i < len; i+=3){
    $set.slice(i, i+3).wrapAll('<div class="test"/>');
} 
Kevin
  • 80
  • 5
0

Another variation on the same idea...

If that HTML pattern is repeated throughout your page, you may want to use jQuery's each() to apply the formula to each block. You can also add flexibility to handle headers with greater or fewer than two siblings.

For each .uniqueClass, I'm using nextUntil() filtered by :lt(), addBack(), and wrapAll().

In English: For each .uniqueClass, find all following siblings until the next .uniqueClass, limit to 2 siblings, add the original selector to the set, and wrap the set with the wrapper element.

var $wrapper = jQuery('<div>', {
  'class': 'wrapper'
});

jQuery('.uniqueClass').each(function() {
  jQuery(this).nextUntil('.uniqueClass', ':lt(2)').addBack().wrapAll($wrapper);
});
.wrapper {
  background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2 class="uniqueClass">Headline</h2>
<p>A p tag always follows.</p>
<div class="accordion">An accordion always comes after the p tag.</div>
<p>But not this one.</p>
<div>And not this one.</div>

<h2 class="uniqueClass">Headline</h2>
<p>A p tag always follows.</p>
<div class="accordion">An accordion always comes after the p tag.</div>
<ul>
  <li>But not this one.</li>
  <li>Nor this one.</li>
</ul>

<h2 class="uniqueClass">Headline</h2>
<p>Maybe this block doesn't have two siblings. That's ok.</p>

<h2 class="uniqueClass">Headline</h2>
<span>One</span>
<span>Two</span>
<span>Three</span>
showdev
  • 28,454
  • 37
  • 55
  • 73