How to store list items in an array using jQuery
I want to store all list items from multiple lists of the same class in an array.
for example:
<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 is returned empty.
thank
+3
source to share
4 answers
There is no need for any complex logic.
You can use the method .get()
to retrieve an array of elements corresponding to a jQuery object:
var arr_list_items = $('.myList li').remove().get();
console.log(arr_list_items);
// [li, li, li, li, li]
Alternatively, you can also use the method .map()
:
var arr_list_items = $('.myList li').remove().map(function () {
return this;
}).get();
+2
source to share
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 cannot explain the code, but I think you can understand it
+1
source to share
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>
0
source to share