mirror of
https://github.com/home-assistant/frontend.git
synced 2025-06-29 21:46:35 +00:00
34 lines
1.1 KiB
JavaScript
34 lines
1.1 KiB
JavaScript
/**
|
|
* Update root's child element to be newElementTag replacing another existing child if any.
|
|
* Copy attributes into the child element.
|
|
*/
|
|
export default function dynamicContentUpdater(root, newElementTag, attributes) {
|
|
const rootEl = root;
|
|
let customEl;
|
|
|
|
if (rootEl.lastChild && rootEl.lastChild.tagName === newElementTag) {
|
|
customEl = rootEl.lastChild;
|
|
} else {
|
|
if (rootEl.lastChild) {
|
|
rootEl.removeChild(rootEl.lastChild);
|
|
}
|
|
// Creating an element with upper case works fine in Chrome, but in FF it doesn't immediately
|
|
// become a defined Custom Element. Polymer does that in some later pass.
|
|
customEl = document.createElement(newElementTag.toLowerCase());
|
|
}
|
|
|
|
if (customEl.setProperties) {
|
|
customEl.setProperties(attributes);
|
|
} else {
|
|
// If custom element definition wasn't loaded yet - setProperties would be
|
|
// missing, but no harm in setting attributes one-by-one then.
|
|
Object.keys(attributes).forEach((key) => {
|
|
customEl[key] = attributes[key];
|
|
});
|
|
}
|
|
|
|
if (customEl.parentNode === null) {
|
|
rootEl.appendChild(customEl);
|
|
}
|
|
}
|