Is there a means of detecting whether an element appears before or after another element in markup? This is regardless of position in DOM. It could be a child, a sibling, a parent or a parent’s parent. This is a general question, so no markup to share.
To clarify – this is in regards to the element’s position in markup, not its display position. Now that I think about it my question is a bit strange because if you have element X and element Y then you can have these scenarios.
//in regards to y
<x />
<y /> //:after
<y /> //:before
<x />
<x><y /></x> //not really before or after is it?
Yes, sort of. DOM3 introduced
Node.compareDocumentPosition, which allows you to compare the position of two elements. The functionality isn’t very friendly: it involves bitmasks: this is a jQuery plugin that should simplify its use.This code is only tested on Firefox 9 and the current version of Chromium. Certainly it won’t work in old versions of IE.
Also, an element that contains another is considered to be before it in the structure.
OK, a little Googling gives me this blog post by John Resig (the creator of jQuery), which includes compatibility with IE <9. (It’s a little ugly: it uses two non-standard bits of functionality:
containsandsourceIndex.) This code should be cross-browser: