Posted By

kouphax on 10/02/08


Tagged

sort array DOM prototype


Versions (?)

Sort Element Array by DOM Position


 / Published in: JavaScript
 

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.

  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
Posted By: kouphax on October 2, 2008

Currently only works with IE and Firefox

You need to login to post a comment.