I'm trying to enclose sections of the dom with a DIV tag. Basically I want all elements between headings (and including the top-most heading) enclosed in a DIV.
My approach is to scan through the DOM, find a header tag, insert an opening DIV tag, continue scanning until I hit the next header, close the prior div, and open a new div tag. Thus: <h2>heading 2a<\h2> ...html tags... <h3>heading 3a<\h3> ...html tags... <h2>heading 2b<\h2> ...html tags... Becomes (indent added for clarity only): <div> <h2>heading 2a<\h2> ...html tags... <\div> <div> <h3>heading 3a<\h3> ...html tags... </div> <div> <h2>heading 2b<\h2> ...html tags... </div> I'm using .before to add the starting <div> tag, but it looks like .before automatically closes open tags. I don't see any mention of this in the docs. How would I go about adding an open ended tag to the DOM? Alternately, is there a way of identifying each section between headers so I can .wrap with a div? Here's the code snippet: var open = false; $('#text').children().each(function(i) { if( this.nodeName.match(/^H\d+$/) ) { if (open) { $(this).before('</div>'); } $(this).before('<div class="xxx">'); open = true; } });