Core JavaScript

Include HTML with AJAX

AJAX is a method for retrieving data from a server without refreshing the web page. This JavaScript code example shows how to use AJAX to include HTML files inside a web page.

IMPORTANT: These files must be accessed via a web server. That is, they must be on a server or served by a web server on a local machine.

IncludeHtml.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>XoaX.net's JavaScript Demo</title>
		<script type="text/javascript" src="IncludeHtml.js"></script>
	</head>
	<body onload="IncludeHTML()">
		<div data-include-html="H1.html"></div> 
		<div data-include-html="Content.html"></div>
	</body>
</html>

IncludeHtml.js

function IncludeHTML() {
	const qaElements = document.getElementsByTagName("*");
	for (let i = 0; i < qaElements.length; ++i) {
		let sFileName = qaElements[i].getAttribute("data-include-html");
		if (sFileName) {
			let qHttpRequest = new XMLHttpRequest();
			qHttpRequest.open("GET", sFileName, true);
			qHttpRequest.onreadystatechange = function() {
				if (qHttpRequest.readyState == 4) {
					if (qHttpRequest.status == 200) {
						qaElements[i].innerHTML = this.responseText;
					} else if (qHttpRequest.status == 404) {
						qaElements[i].innerHTML = "<b>Error:</b> File \"" + sFileName + "\" not found.";
					}
					// Remove the attribute and recurse.
					qaElements[i].removeAttribute("data-include-html");
					IncludeHTML();
				}
			}
			qHttpRequest.send();
			return;
		}
	}
}

H1.html

<h1>HTML File Include</h1>

Content.html

<hr/>
<a href="https://xoax.net/">XoaX.net</a><br /><br />

<div><math><mfrac><mn>22</mn><mn>7</mn></mfrac></math></div>

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
	<circle cx="100" cy="100" r="75" fill="lightgray" stroke="gray" stroke-width="5" />
</svg>
<hr/>
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.