Match each element individually in Selector.findElement since Sizzle.matches does not preserve order

This commit is contained in:
Sam Stephenson 2009-10-10 13:24:04 -05:00
parent 79cf30aab1
commit 4d042a9fa0
3 changed files with 20 additions and 1 deletions

View File

@ -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]);
}
}
},
/**

View File

@ -79,4 +79,10 @@
<div id="counted_container"><div class="is_counted"></div></div>
<div foo-bar="baz" id="attr_with_dash">blah</div>
<div id="container_1" class="container">
<div id="container_2" class="container">
<span id="target_1"></span>
</div>
</div>
</div>

View File

@ -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));
}
});