开发者

Ordering DOM elements

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.


What you're looking for is compareDocumentPosition. PPK has browser compatibility details and John Resig has a version for IE.


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 name attribute, you can use getElementsByName, which will return a collection of the elements in the order they appear in the document:

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

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:

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

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:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜