Calaf Calaf - 4 months ago 28
HTML Question

Alternative to x.innerHTML for long texts

I'm trying to write a form in HTML and JS that shows at the end the completed form uneditable for confirmation.

I have to replace the contents of the page without refresh and/or redirection.

My code is:

function F() {
if(...){
//Empty fields [...]
}else{
var el = document.getElementById("formID"); //Form da sostituire
el.innerHTML = "NEW CONTENT";
}
}


The problem is that the "new content" is really long and is very uncomfortable to write it as a string. Are there any alternatives to innerHTML for this situation?

Answer

Use the <template> tag. Put the content you want inside a <template> tag, give it an ID, and then in JavaScript simply copy the content of the template inside the form.

HTML:

<template id="form-template">
  NEW CONTENT
</template>

JavaScript:

function F() {
    if(...){
         //Empty fields [...]
     }else{
        var el = document.getElementById("formID"); //Form da sostituire
        el.innerHTML = document.getElementById("form-template").innerHTML;
    }
}

See live example in the following snippet:

document.querySelector("button").addEventListener("click", event => {
  document.getElementById("content").innerHTML = document.getElementById("my-template").innerHTML
})
<template id="my-template">
  <h1>Hello template!</h1>
</template>
<button type="button">Try it!</button>
<div id="content"></div>