Last active
November 27, 2021 01:24
-
-
Save james0r/2e9ca3bc751855d24de80a7dae02edcb to your computer and use it in GitHub Desktop.
q5 querySelector Helper Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns matched element or nodelist. | |
* | |
* @param {string} A valid CSS selector. | |
* @param {HTMLElement} An object instance of HTMLElement. | |
* @param {boolean} True uses querySelectorAll and returns a Nodelist. | |
* @return {HTMLElement or Nodelist} Matched element or elements. | |
* Usage: | |
* q5('.some-class') // returns single element in the DOM tree | |
* q5('.some-class', ancestor) // returns single element descendant of parent element | |
* q5('.some-class', ancestor, true) // returns Nodelist of matched descendant elements of ancestor | |
* q5('.some-class', true) // returns Nodelist of matched elements in the DOM tree | |
*/ | |
window.q5 = function (selector, ancestor, all) { | |
if (typeof ancestor === "boolean") { | |
all = ancestor | |
return document.querySelectorAll(selector); | |
} else { | |
if (all) { | |
return (ancestor ? ancestor : document).querySelectorAll(selector); | |
} else { | |
return (ancestor ? ancestor : document).querySelector(selector); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment