Skip to content

Instantly share code, notes, and snippets.

@huntie
Last active January 3, 2022 02:14
Embed
What would you like to do?
A simplified implementation of `document.querySelector()` and `document.querySelectorAll()`, during a workshop on data structures.
/**
* 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;
}
@Bensigo
Copy link

Bensigo commented Oct 2, 2019

Hello, is there a video of this workshop

@huntie
Copy link
Author

huntie commented Oct 3, 2019

Hi @Bensigo! Unfortunately there is no recording. This was a while ago at my previous company and wasn't run by me.

@sevev77
Copy link

sevev77 commented Jan 3, 2022

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