Use append to add block of code to different html files

I am wondering if I can use append to add a template literal (a block of code) to different html files. E.g., let’s say I have a couple of html files ( about.html, projects.html, contact.html) and they all share the same <header>...code here...</header> and <footer>...code here..</footer>, instead of manually adding these block of codes in each one of the html files, can I do this with JS somehow ?

Without more details, I can only say, yes you can.
Check out mozilla for developers for more details.

I edited my post, basically I have a block of code in the header and footer section that I would like to add to different html files, and I was wondering if I can do this with JS instead of manually adding these block of codes in each of the html files.

yes, you can do that with vanilla js or you can use some library, like ejs … it is perfect for what you are trying to do…

You can create separate files like header.html and footer.html which would contain applicable content. Then you would in each page where you want to load the contents of these files, you could create a div for each section like:

<div id="header"></div>
<div id="footer"></div>

Then you would need to put the following in each page or create a function which gets called which contains these load statements.


You can only use this code if the files are serve by a webserver and not just your local pc, because you will received a cross-origin error otherwise.

I can’t do this on my local-host? I can’t use this trick for me development work then.

Are you running a webserver on your local machine? If so, it will work. I just meant you can not just open the file locally like file:///C:/project/index.html

Yes I am. Perfect then! thanks again @RandellDawson

One more question, would this be consider a good practice or would you say it’s better to insert the code in the html files? I just think having a general controller like your example is better for maintainability.

If you were using a server side language like php, you could use php include syntax and directly include the html of the files also. There is no reason to repeat html across multiple files, because if you need to make a change, you would have to manually change each of those sections in the files vs. making a single change which the code above will handle.

1 Like

That’s what I thought, thanks for your help.