The following code creates a WhatsApp button.

How would you improve this code?

document.body.insertAdjacentHTML('beforeend', `
    <aside class="cbwtphone_wrapper">
        <img class="cbwtphone_icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/WhatsApp.svg/1024px-WhatsApp.svg.png"></img>
        <a class="cbwtphone_link" href="https://wa.me:NUMBER">
            <span class="cbwtphone_text">WhatsApp call</span>

newStyle = document.createElement("style");
newStyle.type = "text/css";
newStyle.innerHTML +=`
    .cbwtphone_wrapper {
        display: flex;
    align-items: center;
    justify-content: center;
        position: fixed;
        right: 0;
    bottom: 0;
        left: 0;
        z-index: 2147483647;
        text-decoration: none;
        font-size: 120%;
        font-weight: bold;
    background: linear-gradient(-160deg,#2494db 0%,#0d7ab8 78.66%) /* #149714; */

    .cbwtphone_link {
        text-decoration: none; /* Fixes continuing line problem */
    .cbwtphone_icon {
        width: 50px;
        height: 50px;
    vertical-align: middle;
    .cbwtphone_text {
        vertical-align: middle;
    color: #fff;


1 Answer 1


You shouldn't treat HTML as text strings in your code, because you won't get code completion or error detection in your IDE. Instead, for HTML you can use createElement

let mydiv = document.createElement("div")
mydiv.innerText = "Hello world"

For CSS it's sadly not possible (as far as I know) to create new styles dynamically this way.

  • \$\begingroup\$ What makes you think OP is using an IDE? You're right that manipulating DOM is more type-safe than injecting text representation, of course. \$\endgroup\$ Feb 15, 2023 at 11:12
  • \$\begingroup\$ I don't think many developers code HTML / CSS without an IDE, but I could be wrong. \$\endgroup\$
    – Kokodoko
    Feb 15, 2023 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.