From 4d042a9fa0d3eb2f8e7234e34192b2d0964dec9f Mon Sep 17 00:00:00 2001 From: Sam Stephenson Date: Sat, 10 Oct 2009 13:24:04 -0500 Subject: [PATCH] Match each element individually in Selector.findElement since Sizzle.matches does not preserve order --- src/dom/selector.js | 9 ++++++++- test/unit/fixtures/selector.html | 6 ++++++ test/unit/selector_test.js | 6 ++++++ 3 files changed, 20 insertions(+), 1 deletion(-) 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