tags:

views:

79

answers:

4

We have list in html:

<ul class="list">
<li>some text<li>
<li>some text<li>
<li>some text<li>
<li>some text<li>
<li>some text<li>
...
<li>some text<li>
</ul>

There can be more than 100 <li>

How to do:

1) Add for each <li> id with number, like:

<li id="item1">some text<li>
<li id="item2">some text<li>
...
<li id="item200">some text<li>

and so on, to the end.

2) Count all <li> inside <ul class="list">

3) After second step, if there are more than 60 <li>, add their IDs (item number) to array 1, all other's <li> IDs add to array 2 (from 60 to the end, from 60 to 500 if there are 500 <li>).

Thanks!

+3  A: 

This should work:

var items = $("ul.list").children(),
    size = items.size(),
    firstArray = [],
    secondArray = [];
items.each(function(index, value) {
    if (index < 60) {
        firstArray.push(this);
    }
    else {
        secondArray.push(this);
    }
    index++;
    this.id = "item" + index;
});
ChaosPandion
what is ++index in this case?
Happy
this only the first step, what about second and third?
Happy
index of element inside node.
Artem Barger
For #2, $('ul.list').length()
Radu
+2  A: 
$('ul.list').each(function() {
    var lis = $(this).find('li'),
        count = lis.length,
        first = [],
        second = [],
        overLimit = count > 60;

    lis.each(function(i,o){
        if ( i <60 ) {
           first.push(this)
        } else if ( (i > 60) && overLimit ) {
           second.push(this)
        }

        $(this).attr('id', 'item-' + i);
    })

});
meder
how to print created arrays?
Happy
@WorkingHard did you tried to do something before asking? Read API, googling?
Artem Barger
+2  A: 

For second step:

$( "ul.li").length

And third:

var arr1 = $( "ul.li:lt(60)");
var arr2 = $( "ul.li:gt(60)");

I don't know what exactly do you mean by print but you can took an example from here:

$( arr2).each( function( item) { alert( item);});
Artem Barger
+8  A: 

Step 1:

var $li = $('ul.list > li').attr('id', function(i) { return "item" + (i + 1) });

Step 2:

var count = $li.length;

Step 3:

if(count > 60) {
    var arr1 = $li.slice(0,60);
    var arr2 = $li.slice(60);
}

EDIT: Mis-spelled function. Fixed.

Note: Of course, you don't need a count variable. $li.length can go inside the if() statement.

Note: The .slice() method will return a jQuery object. If you actually want an array, add .get() after .slice(). Or with jQuery 1.4 or later, you can use .toArray().

patrick dw
nice, far more succinct than mine.
meder
+1, gooooooood!
Artem Barger