Skip to content

Commit

Permalink
find[All] works on document fragments
Browse files Browse the repository at this point in the history
  • Loading branch information
chemerisuk committed Mar 24, 2020
1 parent 559ad7d commit 431f832
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 25 deletions.
57 changes: 32 additions & 25 deletions src/node/find.js
Expand Up @@ -20,41 +20,48 @@ function makeMethod(methodName, all) {

if (!node) return all ? [] : new $Node();

const quickMatch = REGEXP_QUICK.exec(selector);
var result, old, nid, context;
let result;

if (quickMatch) {
if (quickMatch[1]) {
// speed-up: "TAG"
result = node.getElementsByTagName(selector);
} else {
// speed-up: ".CLASS"
result = node.getElementsByClassName(quickMatch[2]);
}
if (this instanceof $Document || this instanceof $Element) {
const quickMatch = REGEXP_QUICK.exec(selector);

if (result && !all) result = result[0];
} else {
old = true;
context = node;
if (quickMatch) {
if (quickMatch[1]) {
// speed-up: "TAG"
result = node.getElementsByTagName(selector);
} else {
// speed-up: ".CLASS"
result = node.getElementsByClassName(quickMatch[2]);
}

if (result && !all) result = result[0];
} else if (this instanceof $Element) {
const id = node.getAttribute("id");

if (!(this instanceof $Document)) {
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
if ( (old = node.getAttribute("id")) ) {
nid = old.replace(REGEXP_ESCAPE, "\\$&");

let prefix;
if (id) {
prefix = id.replace(REGEXP_ESCAPE, "\\$&");
} else {
nid = "_<%= prop() %>";
node.setAttribute("id", nid);
prefix = "_<%= prop() %>";
// set fake id attribute value
node.setAttribute("id", prefix);
}

nid = "[id='" + nid + "'] ";
selector = nid + selector.split(",").join("," + nid);
}

result = context["querySelector" + all](selector);
prefix = "[id='" + prefix + "'] ";
selector = prefix + selector.split(",").join("," + prefix);

if (!old) node.removeAttribute("id");
result = node["querySelector" + all](selector);
// cleanup fake id attribute value
if (!id) node.removeAttribute("id");
} else {
result = node["querySelector" + all](selector);
}
} else {
result = node["querySelector" + all](selector);
}

return all ? map.call(result, $Element) : $Element(result);
Expand Down
7 changes: 7 additions & 0 deletions test/spec/element/find.spec.js
Expand Up @@ -78,4 +78,11 @@ describe("find", function() {
expect(DOM.find("details")[0]).toBeUndefined();
});

it("works for fragments", function() {
var fragment = document.createDocumentFragment();
var fragmentEl = DOM.constructor(fragment);

expect(fragmentEl.findAll("*")).toEqual([]);
});

});

0 comments on commit 431f832

Please sign in to comment.