Search code examples
javascripthtmldocumentfragment

Javascript: body.append(content) is not rendered as html


I am building a little piece of html document using javascript templates. const button in the code below is my template. As you can see I replace some content using replace. const button become <button>label</button> and that's fine.

const button = `<button>{try}</button>`;
const newButton = button.replace('{try}', 'label');
const body = document.querySelector('body');

Now I want to append my bew button inside body tag.

body.append(newButton);

It works BUT when I refresh browser I see "<button>label</button>" but I want the rendered version of this html and now I cant see a button but a string <button>.... How can I render this button?


Solution

  • How about using insertAdjacentHTML?

    const button = `<button>{try}</button>`;
    document.body.insertAdjacentHTML(`beforeend`, button.replace('{try}', 'label'));