I have some dynamically created html whole css properties are in an object. So they need to be given using Javascript. So I have used the method below for appending to styles to the dynamically created dom element. I believe it's costly as each time a I'm doing a dom manipulation for appending styles. In the below code itself 10 lines are doing css dom manipulation.
function createNavbar() {
let nav;
nav = '<div class="navbar" id="nav"></div>';
this.body.insertAdjacentHTML("beforeend", nav);
let navBar = document.getElementById("nav");
navBar.style.display = "block"; // style appending begins
navBar.style.background = this.navColors.notice.bg;
navBar.style.color = this.navColors.notice.textColor;
navBar.style.borderWidth = "1px";
navBar.style.borderStyle = "solid";
navBar.style.borderColor = this.navColors.notice.borderColor;
navBar.style.top = this.navPositionValue[this.position].top;
navBar.style.right = this.navPositionValue[this.position].right;
navBar.style.bottom = this.navPositionValue[this.position].bottom;
navBar.style.left = this.navPositionValue[this.position].left; // style appending ends
}
Found a better way from this SO Question, so I used the below line to replace the 10 line code ( used the cssText property )
navBar.style.cssText = `display: block; color: ${this.navColors.notice.textColor}; background: ${this.navColors.notice.bg}; border: 1px solid ${this.navColors.notice.borderColor}; top: ${this.navPositionValue[this.position].top}; right: ${this.navPositionValue[this.position].right}; bottom: ${this.navPositionValue[this.position].bottom}; left: ${this.navPositionValue[this.position].left};`
By using this method I hope the Dom manipulation is reduced to 1 instead of 10, but the line is pretty long and hard to read. I would like to know if there is any better way than this to append long lines or many css in js