3

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?

1
  • you can add code console.info(1111); inside you while,you will find it does not console Commented Jul 10, 2015 at 1:19

4 Answers 4

6
var array = [];
$('.myList li').each(function(i, li) {
  array.push($(li));
});
Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

1
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

Comments

0

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>

Comments

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.