include html in another html

How to Include Another HTML in HTML File

Sometimes you may need to display the content of another HTML file in a given HTML file. In this article, we will learn how to do this using jQuery, which offers an easy to do this. You can also display other HTML files in a web page using plain JavaScript if you want.


How to Include Another HTML in HTML File

Let us say you have the following HTML page b.html.

<html>
<body>
<p>File to be included</p>
</body>
</html>

You can include this page in another HTML page a.html using load() function. Let us say you have the following a.html file and you want to display the above HTML page in the div with id=load_content.

<html>
<body>
<div id="load_content"></div>
</body>
</html>

You can easily do this by adding the following JavaScript.

<script> 
    $(function(){
      $("#load_content").load("b.html"); 
    });
    </script> 

In the above code, we call load() function on load_content div and display b.html file in it. Please note, you need to include jQuery library as shown below, for the above code to work.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

Secondly, the path to html file b.html needs to be relative to that of a.html. In other words, the path to the file to be included should be relative to where it is being referred to.

When a.html is loaded in a web browser, you will see the entire content of b.html displayed inside the div with id=load_content.

In this article, we have learnt how to include another HTML in HTML file. It is useful if you want to display another page’s content in your web page, without rewriting the code. If your website does not use a template system, then this is a good way to display headers and footers on all pages of your websites.

Also read:

How to Call Function When Page is Loaded in JavaScript
How to Match Exact String in JavaScript
How to Convert Columns to Rows in Pandas
How to Set/Unset Cookie With jQuery
How to Abort AJAX Request in JavaScript/jQuery

Leave a Reply

Your email address will not be published.