suryanaga
suryanaga

Reputation: 4002

Run each() function in order of number of parents

I need to run a function once for every element which matches .myClass - But it needs to be run in the order of how many parents each element has.

$('.myClass').each(function(index){
  //my code
});

The only thing I can think of doing is doing another each() function just before that one that appends a data-sort attribute based on the parents().length() but surely there's a better way then that?

Upvotes: 0

Views: 100

Answers (1)

cookie monster
cookie monster

Reputation: 10972

map the number of parents along with the element to an Array of objects. Then sort it and iterate the result.

var els = $('.myClass');

var data = els.map(function(index, el){
  return {el: el, pars:$(el).parents().length};
}).toArray()
  .sort(function(a,b) {
    return a.pars - b.pars;
});

$.each(data, function(i, obj) {
    var el = obj.el;
    // do something with el
});

Upvotes: 4

Related Questions