Todd Vance
Todd Vance

Reputation: 4711

Surrounding elements using JQuery - before() not doing what I want

I have some HTML and I am calling each H1 using .each(). I WANT to not only surround the H1's but all the content below it -until the next H1- with a div.

If I try something like:

$('#presentationcontent h1').each(function (index) {
      $(this).before('<div>');

It closes the div for me... I wanted to do something like this:

 $('#presentationcontent h1').each(function (index) {
        counter++;
        if (counter == 1) 
        {
            $(this).before('<div class="headingSections" style="border: 1px">');
        }
        else
        {
           $(this).before('</div><div class="headingSections" style="border: 1px">');
        }

Hoping that I could set the first H1 to <div> and every other one to close the <div> and open a new one... that way ALL THE CONTENT under the H1 gets included.

Anything?

Upvotes: 1

Views: 205

Answers (2)

Blazemonger
Blazemonger

Reputation: 92943

Try:

$('#presentationcontent h1').each(function (index) {
    $(this).nextUntil('h1').andSelf().wrapAll('<div/>');
    // ...
});

http://jsfiddle.net/7V2fb/1/

Upvotes: 2

Chad
Chad

Reputation: 19609

Making assumptions about your HTML setup, the following would do the trick:

$('#presentationcontent h1').each(function() {
    $(this).nextUntil('h1').andSelf().wrapAll('<div/>');
});

Here is a jsFiddle of it working.

Upvotes: 2

Related Questions