0

I have a problem to seperate a ul list in 5 parts. The list is something like:

<ul class="designer-list">  
<li>7 title</li>
<li>alpha</li>
<li>charlie</li>
<li>charles</li>
<li>lima</li>
</ul>    

with this jQuery I put the first character on top

$(document).ready(function(){

    var lastCharacter = '';
    var list = $('ul.designer-list li');

    list.each(function() {
        var $this = $(this);
        var firstCharacter = $this.text().trim().charAt(0);
        if(firstCharacter != lastCharacter) {

            $this.before('<li class="first-character"><span>'+firstCharacter+'</span></li>');

            lastCharacter = firstCharacter;
        }
    });
});

that makes this: 7 7 title A alpha C Charlie Charles L Lima

That works fine, but I want to separate the list in 5 columns. If I try something like:

 $this.before('</ul></li><li class="first-character"><span>'+firstCharacter+'</span><ul>');

The Browser closes the tag. Does anybody have an idea?

I want the following output:

7     E      K      S     W
List  List   List   List  List
A     F      L      T     X
List  List   List   List  List
muex
  • 120
  • 1
  • 2
  • 7
  • What html structure do you want to end up with? – David Thomas Jun 18 '13 at 08:13
  • I think this question/answer comes quite close to the thing you're trying to achieve: http://stackoverflow.com/questions/9886676/jquery-add-closing-tag-and-then-reopen-when-using-before The main problem also being that the html part is not valid, since it's starting with a closing tag, which jQuery doesn't like much. – René Wolferink Jun 18 '13 at 08:16

1 Answers1

0

Update Answer

Check DEMO http://jsfiddle.net/yeyene/2yg9e/4/

This demo will create a first characet list-divider for all lists in ul.

JQUERY

$(document).ready(function(){
    $('ul.designer-list').each(function() {    
        var lastCharacter = '';
        var list = $(this).find('li');
        
        var e = '';
        list.each(function() {
            var $this = $(this);
            var firstCharacter = $this.text().trim().charAt(0);
            
            if(firstCharacter != lastCharacter) {
                e ='<li class="first-character">'+firstCharacter+'</li>';
                
                // if you want new ul, use this
                /*e ='<ul><li class="first-character">'+firstCharacter+'</li><ul>';*/
                
                lastCharacter = firstCharacter;
                $this.before(e);
            }            
        });        
    });    
});
Community
  • 1
  • 1
yeyene
  • 7,297
  • 1
  • 21
  • 29
  • I need a closing ul after every li.first-character. So I can float these 5 ul and I have the 5 cols. – muex Jun 26 '13 at 07:07
  • check again, now you got 5 ul lists for all first character...http://jsfiddle.net/yeyene/2yg9e/3/ – yeyene Jun 26 '13 at 07:15