tags:

views:

517

answers:

1

I've got a whole bunch of elements that I need to group, but because it's being spat out of some machinery which I can't alter, I need to do so using jquery (which I'm fairly familiar with the basics of)

Basically I've got a load of p tags and divs loose inside a form element (yes bad markup, but that's another story). I need to group the p tags with the following one or two divs inside a fieldset.

I've tried inserting fieldset close and then start tag before each p element, but I guess the machinery that sorts it out wants to insert legal elements, so that doesn't work

+1  A: 

If I understand correctly, you have a document where the markup looks something like this:

<p>paragraph 1</p>
<div>par1 div1</div>
<div>par1 div2</div>
<p>paragraph 2</p>
<div>par2 div1</div>
<div>par2 div2</div>
<p>paragraph 3</p>
<div>par3 div1</div>
<p>paragraph 4</p>
<div>par4 div1</div>

And you want to end up with something like this:

<fieldset>
 <p>paragraph1</p>
 <div>par1 div1</div>
 <div>par1 div2</div>
</fieldset>
<fieldset>
 <p>paragraph2</p>
 <div>par2 div1</div>
 <div>par2 div1></div>
</fieldset>
.....

If this is the case, then this jQuery snippet will do the trick:

$(function(){   
    $('p').each(function(index,item){
      var nextDiv = $(item).next();
      var followingDiv = $(nextDiv).next('div');
      $(item).wrap("<fieldset id='fieldset" + index + "'></fieldset>");
      $("#fieldset"+index).append(nextDiv).append(followingDiv);
    });
});
Jose Basilio
Thanks, I'd come up with something similar, although not as succinct as yours.
chrism
If this answer helped you, please accept it.
Jose Basilio