thiirteen
thiirteen

Reputation: 103

Storing collection of HTML elements in variable for later use

Here is a jQuery issue that I come across and always have to resolve using methods I'm not proud of.

I'm attempting to store a collection of elements for later assessment. The problem is that every time I try to access and apply any function to it, the error console reports the it is not a function. I'm convinced that I have a misunderstand of how jQuery works. Nonetheless, I'd like to be pointed in the right direction. Here is the code I am using:

var products = $('ul.products');
var productLists = []
$.each(products, function (i) {
    productLists[i] = products[i].children('li');
    console.log(productLists[i]);
});

and here is the error I get:

Uncaught TypeError: Property 'children' of object #<HTMLUListElement> is not a function

Upvotes: 3

Views: 2631

Answers (2)

Ankit
Ankit

Reputation: 1887

you can directly use the each method on jquery collection object. So another way of doing the same thing could be:

$('ul.products').each(function(){
  productsList.push( $(this).children("li") );
})

Matter of choice though, I always preferred this approach when dealing with jQuery collection.

Upvotes: 0

Sampson
Sampson

Reputation: 268344

You're attempting to call a jQuery method off an HTMLElement. Try wrapping the element reference in a new jQuery object:

productLists[i] = $(products[i]).children('li');

Within $.each, you can use the keyword this to reference the current item being handled. So instead of calling products[i], you could just as easily say this:

$.each( products, function() {
  productsList.push( $(this).children("li") );
});

Note also that jQuery already stores a collection of references to elements when you make a selection:

var productList = $("ul.products li"); // All list items in ul.products

You can then manipulate all of these as you wish later. If you need your own copies of them, to ensure they will exist later when you want to tamper with them, you can use .clone:

var productList = $("ul.products li").clone();

Upvotes: 6

Related Questions