Sort Element Array by DOM Position


/ Published in: JavaScript
Save to your folder(s)

This function will sort an array of DOM elements in order of the DOM position. Useful when using calls such as $$("img.L,img.M") which doesn;t return a sorted element array.

It uses prototype but you can replace the Prototype.Browser stuff with anything else.


Copy this code and paste it in your HTML
  1. var DOMPositionComparator = function(a,b){
  2. if(Prototype.Browser.IE){
  3. return a.sourceIndex - b.sourceIndex;
  4. }else if(Prototype.Browser.Gecko){
  5. return 3 - (a.compareDocumentPosition(b) & 6);
  6. }
  7. };
  8.  
  9. var sortedFields = $$('img.L,img.M').sort(DOMPositionComparator);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.