Skip to content

Instantly share code, notes, and snippets.

@yulon
Created September 14, 2021 15:18
Show Gist options
  • Select an option

  • Save yulon/0214bb1ea0e8345e359e2e5baf2d4d6f to your computer and use it in GitHub Desktop.

Select an option

Save yulon/0214bb1ea0e8345e359e2e5baf2d4d6f to your computer and use it in GitHub Desktop.
function _basicKuery(args, isQueryAll) {
var root, sel
for (let i = 0; i < args.length; i++) {
if (sel === undefined && typeof args[i] === 'string') {
sel = args[i]
continue
}
if (!root) {
root = args[i]
}
}
if (!sel) {
return null
}
var resultAll
if (isQueryAll) {
resultAll = []
}
if (!root) {
root = document.body
}
var nodes = [{ el: root, isRoot: true }]
while (nodes.length) {
let node = nodes.shift()
let el = node.el
if ('isRoot' in node && node.isRoot) {
if (!isQueryAll) {
let result = el.querySelector(sel)
if (result) {
return result
}
}
let results = el.querySelectorAll(sel)
for (let i = 0; i < results.length; i++) {
resultAll.push(results[i])
}
} else if ('shadowRoot' in el && el.shadowRoot) {
nodes.push({ el: el.shadowRoot, isRoot: true })
}
if (!('children' in el)) {
continue
}
for (let i = 0; i < el.children.length; ++i) {
nodes.push({ el: el.children[i] })
}
}
return resultAll
}
function kuery() {
return _basicKuery(arguments, false)
}
function kueryAll() {
return _basicKuery(arguments, true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment