diff --git a/src/dom/selector.js b/src/dom/selector.js index 60b201c..ee7b308 100644 --- a/src/dom/selector.js +++ b/src/dom/selector.js @@ -77,7 +77,14 @@ **/ findElement: function(elements, expression, index) { if (Object.isUndefined(index)) index = 0; - return Element.extend(Sizzle.matches(expression, elements)[index]); + var selector = new Selector(expression), length = elements.length, matchIndex = 0, i; + + // Match each element individually, since Sizzle.matches does not preserve order + for (i = 0; i < length; i++) { + if (selector.match(elements[i]) && index == matchIndex++) { + return Element.extend(elements[i]); + } + } }, /** diff --git a/test/unit/fixtures/selector.html b/test/unit/fixtures/selector.html index 42abcd4..4cfa29f 100644 --- a/test/unit/fixtures/selector.html +++ b/test/unit/fixtures/selector.html @@ -79,4 +79,10 @@
blah
+ +
+
+ +
+
diff --git a/test/unit/selector_test.js b/test/unit/selector_test.js index 6f11d2e..633b82b 100644 --- a/test/unit/selector_test.js +++ b/test/unit/selector_test.js @@ -404,5 +404,11 @@ new Test.Unit.Runner({ document.body.appendChild(el); this.assertEqual(2, $(el).select('ul li').length); document.body.removeChild(el); + }, + + testFindElementWithIndexWhenElementsAreNotInDocumentOrder: function() { + var ancestors = $("target_1").ancestors(); + this.assertEqual($("container_2"), Selector.findElement(ancestors, "[container], .container", 0)); + this.assertEqual($("container_1"), Selector.findElement(ancestors, "[container], .container", 1)); } }); \ No newline at end of file