Skip to content
Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
39 lines (28 sloc) 765 Bytes

Determine the order of two DOM elements

Inspired by this from PHP, I wanted a utility function to determine whether a given element came before or after another element in the DOM.

{% codeblock lang:javascript %} (function($){ $.order = function($a,$b) {

$a = $a.eq(0);
$b = $b.eq(0);
var c = 'order-test';

$a.addClass(c);

if ($b.hasClass(c)) {
    // elements are the same
    return 0;
}

$b.addClass(c);

var $elements = $('.'+c);
$elements.eq(0).addClass(c+'-first');

if ($a.hasClass(c+'-first')) {
    // $a is first
    return -1;
} else if ($b.hasClass(c+'-first')) {
    // $b is first
    return 1;
}

};

})(jQuery) {% endcodeblock %}

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.