Pablo Darde
Pablo Darde

Reputation: 6402

How to store list items within an array with jQuery

I want to store all list items of several list of the same class within an array.

for exemple:

<ul class="myList">
  <li>item 1</li>
  <li>item 2</li>
</ul>

<ul class="myList">
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
</ul>

Script file:

var arr_list_items = [];

$('ul.myList').each(function(){
  while( !$(this).empty() ) {
    list_item = $(this).find('li:first');
    arr_list_items.push( list_item );
    list_item.remove();
  }
});

The list items are removed, but the array returns empty. Why?

Upvotes: 3

Views: 15058

Answers (4)

74U n3U7r1no
74U n3U7r1no

Reputation: 319

var array = [];
$('.myList li').each(function(i, li) {
  array.push($(li));
});

Upvotes: 6

sbonkosky
sbonkosky

Reputation: 2557

var arr_list_items = [];

$('ul.myList').each(function(){
  $(this).find('li').each(function(){
    arr_list_items.push(this);
    $(this).remove();
  });
});

console.info(arr_list_items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="myList">
  <li>item 1</li>
  <li>item 2</li>
</ul>

<ul class="myList">
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
</ul>

Upvotes: 0

Sky Fang
Sky Fang

Reputation: 1101

var arr_list_items = [];

$('ul.myList').each(function (i,n) {
    $(n).find('li').each(function (j, m) {
        arr_list_items.push(m);
    }).remove();
});

for (var i = 0; i < arr_list_items.length; i++) {
    console.info(arr_list_items[i]);
}

Because I am poor in English, so I can not explain the code,but I think you can understand it

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240878

No need for any complex logic.

You can use the .get() method to retrieve an array of the elements matched by the jQuery object:

Example Here

var arr_list_items = $('.myList li').remove().get();

console.log(arr_list_items);
// [li, li, li, li, li]

Alternatively, you could also use the .map() method:

Example Here

var arr_list_items = $('.myList li').remove().map(function () {
    return this;
}).get();

Upvotes: 3

Related Questions