Skip to content

Commit

Permalink
If parent is specified but undefined/null, don't ignore it
Browse files Browse the repository at this point in the history
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
  • Loading branch information
fregante committed May 25, 2018
1 parent e42a9fd commit bd578b9
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

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

/**
Expand All @@ -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));
Expand Down

1 comment on commit bd578b9

@fregante
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.