0

Is there a more elegant way of achieving the following with jQuery? Is it possible to iterate through all the children, without nesting the each function?

$.each($('.my-class'), function () {
    $.each($(this).children(), function () {
        alert(this.id);
    });
});

EDIT:

What if you have two or more elements with the class name my-class, how do you iterate through all of their children?

Alexander
  • 682
  • 1
  • 9
  • 23

1 Answers1

5

Use a single selector:

$('.my-class > *').each(function () {
  console.log(this.id);
});

Or chain selectors:

$('.my-class').children().each(function () {
  console.log(this.id);
});
zzzzBov
  • 157,699
  • 47
  • 307
  • 349
  • @skobaljic, I have no idea what you're talking about...j/k. I was lazy and used [arrow functions](http://stackoverflow.com/q/24900875/497418) which was a poor choice because the example made use of `this`. – zzzzBov Oct 13 '16 at 20:48
  • @skobaljic It's ES2015/ES6 syntax – Brendan Bullen Oct 13 '16 at 20:52
  • Are you saying it cannot be done the way you did? You are also lazy to explain and therefore I am sad :( – skobaljic Oct 13 '16 at 20:53
  • It still says nothing about the syntax you used `() => {}`. Don't wanna bother you, have a nice day. – skobaljic Oct 13 '16 at 20:57
  • What if you have two or more elements with the class name my-class, how do you iterate through all of their children? – Alexander Oct 13 '16 at 21:00
  • That function will go trough all the collection check this @Alexander https://jsfiddle.net/h7kb0nLt/ – DaniP Oct 13 '16 at 21:01
  • Yes, it actually does, Somehow I got it wrong the first time. Thanks – Alexander Oct 13 '16 at 21:26
  • @skobaljic Here you go, this should give you an idea of what it's about: https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/ but zzzBov's link does cover it with plenty of detail – Brendan Bullen Oct 14 '16 at 22:09
  • Thank you, it is a really nice article, would recommend to others. – skobaljic Oct 15 '16 at 00:47