From bd578b975e35d9f802cb43a900a6d3c83095c76a Mon Sep 17 00:00:00 2001 From: Federico Brigante Date: Fri, 25 May 2018 14:30:16 +0200 Subject: [PATCH] If parent is specified but undefined/null, don't ignore it Given this: const parent = select('nonexistent') const children = select.all('.children', parent) select.all would look in the whole document, instead of just returning "none found in nonexistent" This commit fixes this error and matches jQuery's behavior --- index.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 5a3efd6..22e92e1 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,10 @@ * @return {?Element} The element found, if any */ function select(selector, parent) { + // Shortcut with specified-but-null parent + if (arguments.length === 2 && !parent) { + return null; + } return (parent || document).querySelector(selector); } @@ -15,7 +19,10 @@ function select(selector, parent) { * @return {boolean} Whether it's been found */ select.exists = function (selector, parent) { - return Boolean(select(selector, parent)); + if (parent) { + return Boolean(select(selector, parent)); + } + return Boolean(select(selector)); }; /** @@ -24,6 +31,11 @@ select.exists = function (selector, parent) { * @return {Element[]} An array of elements found */ select.all = function (selector, parent) { + // Shortcut with specified-but-null parent + if (arguments.length === 2 && !parent) { + return []; + } + // Can be: select.all('selector') or select.all('selector', singleElementOrDocument) if (!parent || typeof parent.querySelectorAll === 'function') { return Array.apply(null, (parent || document).querySelectorAll(selector));