Ordering DOM elements

Given two DOM elements, say a and b, how can we determine what comes first in the document?

I am implementing drag and drop for a set of items. And items can be selected in any order, but when they are dragged, those items need to be moved in the "correct" order.

+2


a source to share


2 answers


I think the easiest way is to give them something in common that can be found easily. For example, if they both have the same attribute name

, you can use getElementsByName

that will return a collection of elements in the order they appear in the document:

var els = document.getElementsByName("myName");

      

This els[0]

will contain the first element of the document, els[1]

will contain the second.

With selectors, you can achieve the same by using a combined selector ,

:



var els = document.querySelectorAll("#el1, #el2");

      

The only drawback is that it querySelectorAll()

is only supported by newer browsers (hence IE6 / 7 excluded). An alternative is to use a framework like jQuery :

var els = $("#el1, #el2");

      

+1


a source


What you are looking for is compareDocumentPosition . The PPK contains browser compatibility information and John Resig has an IE version.



+3


a source







All Articles