How to Include HTML in Many Documents Using JavaScript

A simple JavaScript inclusion can automate a lot of redundant H TML editing

Software developers solving a problem.
gilaxia / Getty Images

To display the same content copied over many different pages of your site, with HTML you must manually insert that content. But with JavaScript, just include snippets of code without any server scripts. JavaScript makes updating large websites easier—just update the single script rather than every page on the site.

A great example of the utility of JS over manual HTML rests with copyright statements.

How to Use JavaScript to Insert Content Into HTML

nano editor with html

The process is as simple as defining a JavaScript file then calling it within the HTML through a script tag.

  1. Write the HTML you want to be repeated in the form of a JavaScript file. For a simple copyright insertion, a file with a single line of JS will suffice:

    document.write("Copyright Lifewire, all rights reserved.");

    You must use document.write everywhere you want the script to insert text within the HTML document.

  2. Save your JS file into a separate directory under your webroot, usually includes:

    includes/copyright.js
  3. Open, in an HTML editor, a web page that will display the JavaScript output. Find the location in the HTML where the include file should display, and place the following code there:

    <script type="text/javascript" src="includes/copyright.js"></script>
  4. Add that same code to every relevant page.

  5. When the copyright information changes, edit the copyright.js file. After you've uploaded it, the text will change on every page of your site automatically.

Tips and Advice

Don't forget the document.write instruction on every line of your HTML in the JS file. Otherwise, this process won't work.

Include HTML or text in a JavaScript include file. Anything that can go in a standard HTML file can go in a JavaScript include file. Similarly, JavaScript includes work anywhere in your HTML document, including the head.​

The Web page document won't show the HTML that is included, only the call to the JavaScript script.