Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load partial HTMLs from another HTML?

Tags:

html

I'm writing a book using HTML. If I write it in one html file, the whole code becomes long, so I want to save each chapters to different files and load them in main html. I mean there are files like chapter1.html, chapter2.html, ... and I want to include the contents of them in the other file main.html.

Is this possible?


1 Answers

If you wish to do this dynamically. you can use javascript instead of <iframe>. Save the HTML content you want to include inside content.html

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("data-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("data-include-html");
          includeHTML();
        }
      } 
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}
</script>

You can Add it to the HTML page Later like below.

<div data-include-html="content.html"></div>
like image 198
Thusitha Wickramasinghe Avatar answered Mar 30 '26 11:03

Thusitha Wickramasinghe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!