0

I have an array of elements, for an easier example, lets just use some numbers:

var items = new Array('1','2','3','4','5','6','7','8','9','10');

From this array, i want to create 4 unordered list, so every list has 3 items in it, like this:

<ul>
    <li>0</li>
    <li>1</li>
    <li>2</li>
</ul>
<ul>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
...

This is what i got so far, but i'm stuck here, i don't know how to proceed:

var ul = $('<ul>',{'class':'test'});
$.each(items,function(index,value){
    if(index%3) {
        //...
    }
    var li = $('<li>').append(value);
    ul.append(li);
});

Demo: http://jsfiddle.net/AzmZq/

1
  • if you want to create 4 unordered list, so every list has 3 items in it, the array must be of size 12 Commented Mar 12, 2013 at 15:57

2 Answers 2

3

$.each is overused. I would just use a basic for loop nested inside a while loop, using Array.shift() to remove array items one at a time:

while (items.length) {
    var ul = $('<ul>', { 'class': 'test' });
    for (var i = 0; i < 3; i++) {
        if (items.length) { // so we don't append empty list items at the end
            var li = $('<li>').append(items.shift());
            ul.append(li);
        };
    };
    $('body').append(ul);
};

http://jsfiddle.net/mblase75/UwDdv/


However, if you insist on the jQuery approach, you need to append and re-initialize the ul each time index%3==0:

var items = new Array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
var ul;
$.each(items, function (index, value) {
    if (index % 3 == 0)  {
        $('body').append(ul);
        ul = $('<ul>', {'class': 'test'});
    }
    var li = $('<li>').append(value);
    ul.append(li);
});
$('body').append(ul);

http://jsfiddle.net/mblase75/zUyRM/

1

Using $.map:

var $ul = $("<ul>").append($.map(items, function(s) { return $("<li>").text(s) });

The day ES6 comes to all browsers, everybody will be happier (for now, we can use Babel):

let $ul = $("<ul>").append(items.map(item => $("<li>").text(item)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.