views:

51

answers:

1

Below is my HTML content

<HR><HR><H3>Document_1</H3>
    <PRE>PART2_1</PRE>
    <PRE>PART2_2</PRE>
<HR><HR><H3>Document_2</H3>
    <PRE>PART3_1</PRE>
    <PRE>PART3_2</PRE>
    <PRE>PART3_3</PRE>

I want to wrap all the elements between <HR><HR><H3>......<PRE></PRE> into different DIVs. In other words I will have 2 <DIV>. I have tried various selectors but unable to get the right jquery.

+1  A: 
var h3 = $('hr+hr+h3'), prev = $(h3).prevAll('hr'), div = $('<div>'), next = $(h3).nextAll('pre')
if ( prev.length && h3.length == 1 && next.length ) {
    $(h3).after(div).appendTo(div)
    $(prev).prependTo(div)
    $(next).appendTo(div)
}

You can probably use that as an example if I misunderstood.

meder
Sorry for confusion! I wanted my output to be <div><HR><HR><H3>Document_1</H3> <PRE>PART2_1</PRE> <PRE>PART2_2</PRE></div><div> <HR><HR><H3>Document_2</H3> <PRE>PART3_1</PRE> <PRE>PART3_2</PRE> <PRE>PART3_3</PRE><div>
I updated it per your update. LMK if it doesnt work.
meder
Mine would work for one set, you'd need to probably use .each if there are multiple sets exactly like that. See if you can solve it :)
meder
@meder - it's not as simple as you think to add `.each` here - `nextAll` will select all `<pre>` tags, even after other `h3`s. This could work if you'll go from last to first - by moving siblings into the div. either way, this is complex for jQuery...
Kobi
Well yeah I guess you'd need some other function to handle the whole sibling business.. which brings me to my next question - why is the markup like this? What are all the possible combinations of this markup?
meder