Last active
January 3, 2022 02:14
-
-
Save huntie/298752eed8e79f3937fb52604a9ed18b to your computer and use it in GitHub Desktop.
A simplified implementation of `document.querySelector()` and `document.querySelectorAll()`, during a workshop on data structures.
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
/** | |
* Run a callback over all children of a given element using depth-first | |
* traversal. | |
* | |
* @param {HTMLElement} element | |
* @param {Function} callback | |
*/ | |
function iterateDOM(element, callback) { | |
const nodes = []; | |
nodes.push(element); | |
do { | |
element = nodes.shift(); | |
callback(element); | |
nodes.unshift(element.children); | |
} while (nodes.length > 0); | |
} | |
/** | |
* Determine if an element matches a given string query. | |
* | |
* @param {HTMLElement} element | |
* @param {string} query | |
* | |
* @return {bool} | |
*/ | |
function matchElement(element, query) { | |
return element.tagName === query.toUpperCase() || | |
element.classList.contains(query); | |
} | |
/** | |
* Return the first element matching the given query. | |
* | |
* @param {string} query | |
* | |
* @return {HTMLElement} | |
*/ | |
function querySelector(query) { | |
return querySelectorAll(query)[0]; | |
} | |
/** | |
* Return all elements matching the given query. | |
* | |
* @param {string} query | |
* | |
* @return {HTMLElement[]} | |
*/ | |
function querySelectorAll(query) { | |
const elements = []; | |
iterateDOM(this, function(element) { | |
if (matchElement(element, query)) { | |
elements.push(element); | |
} | |
}); | |
return elements; | |
} |
Hi @Bensigo! Unfortunately there is no recording. This was a while ago at my previous company and wasn't run by me.
As you loop elements in each level, it should be Breadth-First rather then Depth-First right?
I think you can implement the Depth-First with recursion.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, is there a video of this workshop