views:

62

answers:

2

What's the best way to wrap multiple elements. I've tried several methods but without success.

This is the markup:

<div>
   <h3>Civil aerospace </h3>
   <p>Powering more than 30 civil aircraft types from small executive jets to the lartest airliners.</p>
   <h4>£47.1bn</h4>
   <p>Order book</p>
   <h4>£4,481m</h4>
   <p>Revenue</p>
</div>

This is what I need to end up with:

<div class="hub">
   <h3>Civil aerospace </h3>
   <p>Powering more than 30 civil aircraft types from small executive jets to the lartest airliners.</p>
    <div class="wrap">
     <h4>£47.1bn</h4>
     <p>Order book</p>
     </div>
    <div class="wrap">
     <h4>£4,481m</h4>
     <p>Revenue</p>
    </div>
</div>

Have tried add, find, filter etc

Do I need to set an iteration?

+1  A: 

You can use the new nextUntil() method to do this:

$(function(){
  $("h4").each(function(){
     $(this).add($(this).nextUntil("h4")).wrap("<div class='wrap' />");
  });
});

The nextUntil method is new in jQuery 1.4.

Scharrels
+1  A: 

Sorry, had to nip out for a fry-up :)

Scharrels has it right, but here's a possible solution for jQuery 1.3.2 as well:

$(function(){
    $('div').addClass('hub').find('h4').wrap('<div class="wrap"></div>');
    $('.wrap').each(function(){
        var div = $(this);
        div.append(div.next('p').remove());

        while(div.next('p').length != 0)
            div.append(div.next('p').remove());
    });
});

It's a bit fiddly but it works, and it does cater for there being multiple <p> tags after each <h4>.

Mark B
Although it will most likely not be a problem,, be aware that removing DOM elements in jQuery will remove all events associated with it. If you have an event handler bound to the `<p>` element or any of its children, you have to bind it again.
Scharrels
Good point, worth knowing.
Mark B
Apologies, internet was down here for a few hours :(Thanks Scharrels and Mark B - both solutions worked well. I'm going for the Mark B's as I need to run 1.3.2 versionThanks so much for your help!
donwest