Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a DOM-like element tree from JSONML
function isObject(obj) {
if (!obj) return false;
if (typeof obj !== "object") return false;
if (Array.isArray(obj)) return false;
return true;
}
class Element {
constructor(tagName, attributes, ...children) {
this.tagName = tagName;
this.attributes = { ...attributes };
this.children = children;
}
get innerText() {
return this.children.reduce(
(textContent, child) =>
textContent +
(child instanceof Element ? child.innerText : String(child)),
""
);
}
find(tagName, ...tagNames) {
if (tagName === "#") return this.innerText;
const child = this.children.find(
child => child instanceof Element && child.tagName === tagName
);
if (!child) return undefined;
if (!tagNames.length) return child;
return child.find(...tagNames);
}
}
function createElement(tagName, ...children) {
const attributes = {};
if (isObject(children[0])) {
Object.assign(attributes, children.shift());
}
return new Element(
tagName,
attributes,
...children.map(child => {
if (!Array.isArray(child)) return String(child);
return createElement(...child);
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.