2

I am trying to break down a long unordered list into smaller pieces like this:

$('.cList').each(function() {
    var thisList = $(this).find('li')
    var thisLen = thisList.length
    for(var x=0;x<thisLen;x++) {
        if((x % 5)==0&&x>0) {
            $(thisList).eq(x).after("</ul><ul>")    
        }    
    }
})

What I end up with is this:

<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<ul></ul> <---- I want the list to end and start, not make a nested list

instead of this:

<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul><ul>  <--- like this

It's as if inserting </ul><ul> is not valid HTML and jQuery is somehow decidng that <ul></ul> is valid.

See: http://jsfiddle.net/MGHt5/

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • 3
    When you ask jQuery to insert HTML, it creates a set of DOM element out of the given HTML, then inserts those DOM elements. So, in your example, the `` is superfluous. The `
      ` results in a new list, and that is inserted into the DOM. As such, if you want to break a list up, you're going to have to create a new list, remove the list items from the old list, add them to the new list, and the insert the new list after the current list.
    – Conspicuous Compiler Aug 24 '11 at 16:13
  • possible duplicate of [jQuery split long ul list in smaller lists](http://stackoverflow.com/questions/1644668/jquery-split-long-ul-list-in-smaller-lists) – Shawn Chin Aug 24 '11 at 16:16
  • The code in the duplicate worked for me. – Diodeus - James MacFarlane Aug 24 '11 at 16:34

1 Answers1

7

Instead of worrying specifically about open- and close-tags, I'd use .wrapAll() to wrap <ul> tags around a jQuery object containing 5 <li>s. You can use .slice() to grab chunks of <li>s from thisList.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710