How to add external HTML page to my current page which is another HTML

Viewed 397

I am working on a project where I have to add external HTML files as a header and footer in the main (Index.html) page. I tried below script, but it didn't work

<!DOCTYPE html>
<html lang="en">
<head>
  <title>sample test</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  

  <script>
$(document).ready(function(){
   
   $('#header1').load("mainheader.html");

});
</script>
</head>
<body>
<div id="header1"></div>
</body>
</html>
4 Answers

You can use iframe tag to load another html file or url.

<iframe src="your-html-route/another.html"></iframe>

Use JavaScript and work with components. Then you can work with modules to import or export a component and add HTML with

document.queryselector('#header').innerHTML = '<header>content</header>';

PHP is better for such a thing if you ask me. Make you header and footer in another .php file and include them on every page where you want use them.

Your script $('#header1').load("mainheader.html"); is correct. The fact is that the load() method (just like ajax) works exclusively on the SERVER. In order to load an external page to your tag using the load() method, you need to put your project on the server, or deploy a local server on your computer. There are many programs for this, for example: OpenServer, Denwer, WampServer, XAMPP, etc. I advise you to use OpenServer. It's free and easy to use. After you deploy your local server, you push your project to your server and the load() method will load your external html file.

If it's only a short bit of code then you could use this:

 <pre>
  <code>
    HTML code goes
    here.
  </code>
 </pre>
Related