Skip to content

Instantly share code, notes, and snippets.

@Odepax
Created September 21, 2019 10:37
Show Gist options
  • Save Odepax/480831190d861ae8435c8a4b34107451 to your computer and use it in GitHub Desktop.
Save Odepax/480831190d861ae8435c8a4b34107451 to your computer and use it in GitHub Desktop.
Javascript DOM extensions
/** Converts given string into DOM tree, and extract elements marked with 'id' attributes. */
Document.prototype.parseElements = function parseElements(/** @type {string} */ htmlString) {
const div = this.createElement("div")
div.innerHTML = htmlString
const identifiedElements = {}
for (const element of div.querySelectorAll("[id]")) {
identifiedElements[element.getAttribute("id")] = element
element.removeAttribute("id")
}
return [ div.children, identifiedElements ]
}
Node.prototype.appendChildren = function appendChildren(/** @type{Iterable<HTMLElement>} */ htmlCollection) {
for (const element of htmlCollection) {
this.appendChild(element)
}
return htmlCollection
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment