Skip to content

Instantly share code, notes, and snippets.

@pluma
Created November 12, 2017 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.
Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.
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