Search code examples
javascripttypescriptbuttontexticons

How to create a Button with Icon and text in typescript


I tried to create a button with text and icon. First I tried it in HTML.

    <button>
      <img src="img/favicon.png" alt="Image" width="30px" height="30px" >
      Button Text
    </button>

Second I tried it with TypeScript.

    const btn = document.createElement("button");
    const img=document.createElement("img");
    img.src=`img/${favicon.png}`;
    btn.appendChild(img);
    btn.textContent=label;

After I added the label the Icon will not apear.

My Solution is now

    const btn = document.createElement("button");
    const img=document.createElement("img");
    img.src=`img/${favicon.png}`;
    btn.appendChild(img);
    const span=document.createElement("span");
    btn.appendChild(span)
    span.textContent=label

...

But with this solution I have other problems. Know anyone a better solution? I don't want to use awesome

created with pur HTML


Solution

  • Your first JS solution does not work because setting textContent removes everything that was in the button. See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

    In order to recreate what you did with HTML using JS, you can use the Text object. See https://developer.mozilla.org/en-US/docs/Web/API/Text

    Here a repl : https://replit.com/@billuc/IconButton#index.html

    Code :

        const btn = document.createElement("button");
        const img = document.createElement("img");
        const text = new Text(" Button text");
        img.src = `img/favicon.png`;
        img.alt = "Icon";
        img.width = "10";
        img.height = "10";
        btn.appendChild(img);
        btn.appendChild(text);
        document.body.appendChild(btn);