tags:

views:

76

answers:

3

I have a long list like this:

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
    <li>item 5</li>
    <li>item 6</li>
    <li>item 7</li>
    <li>item 8</li>
    <li>item 9</li>
    <li>item 10</li>
    <li>item 11</li>
    ...
</ul>

and I want to somehow wrap some divs around them like this:

<ul>
    <div>
        <li>item 1</li>
        ...
        <li>item 6</li>
    </div>

    <div>
        <li>item 7</li>
        ...
        <li>item 12</li>
    </div>

    <div>
        ...
    </div>
</ul>

How can I accomplish this?

I tryed .after('</div><div>'); but it's not working, it adds a <div></div>.

A: 

You cannot (well, you can, but you should not) insert DIV elements in a list, since UL can only contain LI elements.

What you can do, is create a nested list UL-> LI -> UL -> LI, LI, LI. Another solution is to assign some specific CSS class to the items that have to be bound together and then apply some specific style to those elements.

UPDATE: if you really need to do that, you can try this:

var d= $("ul").prepend("<DIV />");
var itms = $("ul li:lt(6)");
d.append(items);
naivists
Well I think the question is not that: I insert ul or div, is that how to wrap every 6 li-s in a tag ...
blackhandr
use the `:lt(x)` selector to find first x elements in your set. Then `append()` to the nesting element (see my updated post)
naivists
A: 

You can use jquery wrap :

$('li').each(function() {
     $(this).wrap($('<div/>', { 'class': 'myClass'}));
   });

This should wrap every li with <div class="myClass"> at the beginning and </div> at the end of every div.

c0mrade
A: 

You can do this to quickly wrap them resulting in proper HTML like this:

var lis = $("ul li");
for(var i = 0; i < lis.length; i+=6) {
  lis.slice(i, i+6).wrapAll("<li class='li_group'><ul></ul></li>");
}

This results in:

<ul>
  <li class='li_group'>
    <ul>
      <li>item 1</li>
      <li>item 2</li>
      <li>item 3</li>
      <li>item 4</li>
      <li>item 5</li>
      <li>item 6</li>
    </ul>
  </li>
  <li class='li_group'>
    <ul>
      <li>item 7</li>
      <li>item 8</li>
      <li>item 9</li>
      <li>item 10</li>
      <li>item 11</li>
      <li>item 12</li>
    </ul>
  </li>
  ...      
</ul>

Just style li_group however you want visually.

Nick Craver