Skip to content

Instantly share code, notes, and snippets.

@LeaVerou
Last active August 1, 2020 08:59
Show Gist options
  • Save LeaVerou/6d2c98b896e61d3357ec7c7335609c9d to your computer and use it in GitHub Desktop.
Save LeaVerou/6d2c98b896e61d3357ec7c7335609c9d to your computer and use it in GitHub Desktop.
Build subset of DOM tree from list of unordered DOM elements
// See https://twitter.com/LeaVerou/status/1288721937288638465
function buildGraph(elements) {
let elements = new Set(elements);
const className = "almanac-2020"; // anything sufficiently unique
let map = new Map(); // keep pointers to each element's object
let ret = [];
for (let element of elements) {
// Create initial objects
map.set(element, {element, children: []});
// Add class to elements so we can find them with .closest()
// If that's not an option, we can always loop on .parentNode and check if elements.has(el)
element.classList.add(className);
}
// Recursively build tree
for (let element of elements) {
let ancestor = element.parentNode.closest?.("." + className);
let obj = map.get(element);
if (ancestor) {
let o = map.get(ancestor);
o.children.push(obj)
}
else {
// Top-level
ret.push(obj);
}
}
// CLeanup
elements.forEach(el => el.classList.remove(className));
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment