How to Include HTML in Many Documents Using JavaScript

A simple JavaScript inclusion can automate redundant HTML editing

To display the same content on different pages of your site, with HTML you must manually insert that content on each page. But with JavaScript, you only need to include snippets of code without any server scripts. JavaScript makes updating large websites easier. All you need to do is update the single script rather than every page on the site.

An example of the utility of JavaScript over manual HTML can be seen in the copyright statements that appear on every page of a website.

How to Use JavaScript to Insert Content Into HTML

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

nano editor with html
  1. Write the HTML you want to be repeated in the form of a JavaScript file. For a simple copyright insertion, create a file with a single line of JS, for example:

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

    Use document.write everywhere you want the script to insert text within the HTML document.

  2. Save the JavaScript file to a separate directory under your webroot, this is usually the includes directory.

    includes/copyright.js
    
  3. Open an HTML editor and open 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:

    
    
  4. Add that same code to every relevant page.

  5. When the copyright information changes, edit the copyright.js file. After you upload 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 JavaScript 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.

Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Include HTML in Many Documents Using JavaScript." ThoughtCo, Sep. 30, 2021, thoughtco.com/html-in-many-docs-with-javascript-3468862. Kyrnin, Jennifer. (2021, September 30). How to Include HTML in Many Documents Using JavaScript. Retrieved from https://www.thoughtco.com/html-in-many-docs-with-javascript-3468862 Kyrnin, Jennifer. "How to Include HTML in Many Documents Using JavaScript." ThoughtCo. https://www.thoughtco.com/html-in-many-docs-with-javascript-3468862 (accessed March 19, 2024).