Home > OS >  Looking for a better way of inserting html code into Javascript
Looking for a better way of inserting html code into Javascript

Time:12-14

I want to make insert a long, massive HTML code to an html element using Javascript. I know innerHTML is a good way to do that, but inserting long html code using InnerHTML is very hard to edit later.

Here is an example:

function display(){
document.getElementById('result').innerHTML = '<div><form id="form" ><p style="border: 2px solid #a1a1a1;background: #dddddd; width: 300px; border- radius: 25px; height:60px;"><b>Search Engine</b><br /></p> <input style = "margin-bottom:20px"id="search" type="button" value="Search"></input></p>'
}
<div id=result></div>
<button onclick='display()'>Display</button>
I have a very massive html code to insert and it is very hard for me to edit.

Could anyone suggest me an easier way to insert html code or a better solution of doing this?

Thanks for any responds!

CodePudding user response:

You can use a template literal so that you can have more readable formatting.

document.getElementById('result').innerHTML = `
<div>
  <form id="form">
    <p style="border: 2px solid #a1a1a1;background: #dddddd; width: 300px; border- radius: 25px; height:60px;">
      <b>Search Engine</b>
      <br />
    </p>
    <input style="margin-bottom:20px" id="search" type="button" value="Search"></input>
    </p>
`;
  • Related