Created
September 7, 2023 07:32
-
-
Save osbre/88f43cff7409cefd6932a8da30939464 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Re-creates all <template> tags within <svg> elements as "DOM" elements to overcome browser limitations. | |
* This is necessary because HTML tags inside an SVG element have an SVG namespace, which may lack proper support. | |
* https://github.com/whatwg/html/issues/3563 | |
* https://github.com/alpinejs/alpine/issues/637#issuecomment-654856538 | |
*/ | |
const recreateTemplates = (templates: NodeListOf<Element>) => { | |
let el: Element, | |
template: HTMLTemplateElement, | |
attrs: NamedNodeMap, | |
attr: Attr, | |
count: number, | |
child: Node, | |
content: DocumentFragment; | |
for (let i = 0; i < templates.length; i++) { | |
el = templates[i]; | |
template = el.ownerDocument.createElement('template'); | |
el.parentNode.insertBefore(template, el); | |
attrs = el.attributes; | |
count = attrs.length; | |
while (count-- > 0) { | |
attr = attrs[count]; | |
template.setAttribute(attr.name, attr.value); | |
el.removeAttribute(attr.name); | |
} | |
el.parentNode!.removeChild(el); | |
content = template.content; | |
while ((child = el.firstChild!)) { | |
content.appendChild(child); | |
} | |
} | |
} | |
document.addEventListener('alpine:init', () => { | |
recreateTemplates(document.querySelectorAll('svg template')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment