frontend/js/common/dom/dynamic_content_updater.js
Paulus Schoutsen 912969111f
Move all of hassUtil to JS (#1153)
* Move all of hassUtil to JS

* Fix tests
2018-05-09 21:33:31 -04:00

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);
}
}