javascript - Sort array containing DOM elements according to their position in the DOM -
context
i've structured jquery plugin i'm working on in way has me storing dom elements in array, being able store more information next these elements without having use not-so-fast data().
that array looks like:
[ { element: domelement3, additionaldata1: …, additionaldata2: … }, { element: domelement1, additionaldata1: …, additionaldata2: … }, { element: domelement2, additionaldata1: …, additionaldata2: … }, ] the way plugin works prevents me pushing these elements array in predictable order, means domelement3 can in fact find @ index lower domelement2's.
however, need these array elements sorted in same order dom elements contain appear in dom. previous example array, once sorted, this:
[ { element: domelement1, additionaldata1: …, additionaldata2: … }, { element: domelement2, additionaldata1: …, additionaldata2: … }, { element: domelement3, additionaldata1: …, additionaldata2: … }, ] this is, of course, if domelement1 appears before domelement2 in dom, , domelement2 before domelement3.
discarded solution
the jquery add() method returns set of dom elements in same order appear in dom. using this, requirement work jquery collection – means i'd have refactor huge chunk of abovementioned plugin use different storage format. that's why consider last-resort solution.
another solution?
i have imagined map() , sort of global dom index tied each dom element have done trick, there doesn't appear such "global dom index".
what approach can think of? (if writing code, both vanilla js , jquery welcome.)
there useful function called comparedocumentposition, returns number based on 2 elements relative each other. can use in .sort callback:
yourarray.sort(function(a,b) { if( === b) return 0; if( !a.comparedocumentposition) { // support ie8 , below return a.sourceindex - b.sourceindex; } if( a.comparedocumentposition(b) & 2) { // b comes before return 1; } return -1; });
Comments
Post a Comment