There's an HTML page with 3 elements containing a class of ".list". Those ".list" elements have "li" elements in them, and in those "li" elements, there is text. I'd like to loop through all of "li" elements, and push their text to an array, with jQuery.
This is what I have so far:
var arr = [];
$(".list").each(function() {
this.children("li").each(function() {
arr.push(this.innerHTML);
});
});
However, I'm getting an error back from the console.
Error:
Uncaught TypeError: undefined is not a function
What am I doing wrong, and how can I fix it?
The value of this in your .each() loop will be a reference to an element, not a jQuery object. Thus:
$(".list").each(function() {
$(this).children("li").each(function() {
arr.push(this.innerHTML);
});
});
That is, $(this).children instead of this.children.
Note that you could avoid the outer .each() (not that there's anything terrible about it):
$(".list > li").each(function() {
arr.push(this.innerHTML);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With