madrobby/zepto — Issue #320: emptyArray becomes non-empty
Author: pamelafox
Created: 2011-11-19 18:15:13+00:00
State: open

In $.qsa, it returns emptyArray if it detects an ID string but finds no elements. For some reason, my emptyArray variable contained a reference to a DOM element from a plugin I'm using which meant that it returned a 1-length array with the wrong element instead.

I fixed this by simply returning '[]' instead of emptyArray.

It's quite likely that all my finagling with jQuery plugins and Zepto resulted in the issue, so maybe it won't happen for other people.

It was difficult to debug because of the quadruple nested ternary operator in the $.qsa function - I ended up unwrapping it into:

$.qsa = $$ = function(element, selector){
var found;
if (element === document && idSelectorRE.test(selector)) {
found = element.getElementById(RegExp.$1);
return found && [found] || [];
} else if (classSelectorRE.test(selector)) {
return slice.call(element.getElementsByClassName(RegExp.$1));
} else if (tagSelectorRE.test(selector)) {
return slice.call(element.getElementsByTagName(selector));
} else {
return slice.call(attemptQuerySelectorAll(element, selector));
}
}

I imagine that ternary operators compress better than if/else, but I find them quite hard to understand (especially if I didn't write them to begin with). So, my outsider perspective: the less nested ternarys, the more approachable the code.