Context
I structured the jQuery plugin that I am working on now, so that I store DOM elements in an array, mainly in order to store additional information next to these elements without the need to use data() not so fast.
This array looks like this:
[ { element: DOMElement3, additionalData1: …, additionalData2: … }, { element: DOMElement1, additionalData1: …, additionalData2: … }, { element: DOMElement2, additionalData1: …, additionalData2: … }, ]
The way this plugin works is stopping me from dragging these elements into an array in a predictable order, which means that DOMElement3 may actually end up with an index below DOMElement2 .
However, I need these array elements to sort in the same order as the DOM elements that they contain are displayed in the DOM. The previous sample array, after sorting, will look like this:
[ { element: DOMElement1, additionalData1: …, additionalData2: … }, { element: DOMElement2, additionalData1: …, additionalData2: … }, { element: DOMElement3, additionalData1: …, additionalData2: … }, ]
This, of course, if DOMElement1 appears before DOMElement2 in the DOM and DOMElement2 before DOMElement3 .
Discarded solution
The jQuery add() method returns a set of DOM elements in the same order as in the DOM. I could use this, but the requirement is that I work with the jQuery collection, which means that I will have to reorganize a huge piece of the above plugin to use a different storage format. Therefore, I consider this a decision of last resort.
Another solution?
I would suggest that map() and a kind of global DOM index bound to each DOM element would do the trick, but there isn’t such a “global DOM index”.
What approach can you come up with? (When writing code, both vanilla JS and jQuery are welcome.)