Given two DOM elements, say a and b, how can we determine which comes first in the document?
I’m implementing drag and drop for a set of elements. And the elements can be selected in any order, but when they are dragged, these elements need to be moved in the “correct” order.
I think the easiest way is to give them both something common that can be easily looked up. For instance, if they both have the same
nameattribute, you can usegetElementsByName, which will return a collection of the elements in the order they appear in the document:Here
els[0]would contain the first element of the document,els[1]would contain the second.Using selectors, you could achieve the same thing by using the combining
,selector separator:The only downside is that
querySelectorAll()is only supported by newer browsers (so IE6/7 are ruled out). The alternative is to use a framework like jQuery: