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
You’re attempting to call a jQuery method off an HTMLElement. Try wrapping the element reference in a new jQuery object:
Within
$.each, you can use the keywordthisto reference the current item being handled. So instead of callingproducts[i], you could just as easily saythis:Note also that jQuery already stores a collection of references to elements when you make a selection:
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: