Getting element `index` out of the `$.initialize` loop.
IrvingArmenta-ML opened this issue · comments
Hello, I'm trying to get the index number of the elements out in the $.initialize
loop, like this:
$.initialize('.element', function(i,el) {
console.log(i) // this always return: 0
});
What I want to achieve, is the same functionality as $.each
or $.map
to count and distinguish the elements in the DOM, but I keep getting 0
on index
, however the DOM nodes
are shown correctly on el
.
Is there a solution for this?
I think concept of element index is not relevant here as it's calling this callback as soon as element has appeared on the screen, so it has no context of 'group' like map
or each
has.
Consider such case
Initially you have 5 .element
divs
Then you add 2 more .element
divs
Then you remove 3 of existing .element
divs
Then you add one more ----> what would you expect now to be i
inside this function?
I will expect the same result I get using $.each
or $.map
, to get the actual length of the elements that are exactly at that time in the DOM, in your example:
5 .element
divs (0,1,2,3,4)
add 2 = 7 .element
divs (0,1,2,3,4,5,6)
remove 3 = 4 .element
divs (0,1,2,3)
add 1 = .element
divs (0,1,2,3,4)
You can do this by setting a function with $.each
and run a function to "read" again the elements in the DOM, but that is exactly what I want to $.initialize
to do for me, I don't want to set up a function to update
the list of elements.
An iterator doesn't exactly make sense in this context since elements can be inserted into the DOM out of order, and also can appear in complex or nested trees, not just as siblings.
If you are insistent on this, you can off course do:
var i = 0;
$.initialize('.element', function(el) {
console.log(i);
i++;
});
Although I understand that it may make sense to have an iterator in some circumstances, nobody has asked for such a feature to date. I wonder for the sake of curiosity what your scenario is that you need this for?
Wontfix.