Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through classes, and obtain their list item's innerHTML jQuery

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?

like image 384
Elegant.Scripting Avatar asked Nov 22 '25 01:11

Elegant.Scripting


1 Answers

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);
});
like image 155
Pointy Avatar answered Nov 24 '25 15:11

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!