Search code examples
javascriptjquerywrapall

Jquery Complex wrap around uncontained group of items


I'm trying to take group of headers and lists, and contain them individually so I can style them. ie:

<h2>Title 1</h2>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<h2>Title 2</h2>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

I attempted this by using .before() and .after to add a div before the h2 tag, and close it after each ul however I found out that jquery cleans and closes the tag automatically. So I'm guessing I need to use wrap() just not sure how to group the title and list together.


Solution

  • Use

    $('h2').each(function(){
       var self = $(this);
       self.add( self.next() ).wrapAll('<div/>');
    });
    

    demo at http://jsfiddle.net/gaby/e4f9h/